I have a class Father and an inherited class Child. Inside the Child's constructor I want to pass a Father class to cast all Father's properties.
This is my code
class Father
{
int prop1;
int prop2;
// many more properties;
}
class Child : Father
{
string _name;
int _age;
//etc...
public Child(string Name, int Age, Father father)
{
this._name = Name;
this._age = Age;
base = father; //<== this is what I mean to do
}
I know I can't do this directly. What is the right way?
This is complete code, some code is in spanish
class AuditRegistry : Audit
{
protected string _cud;
protected int _employee, _consecutive;
protected DateTime _date;
public string CUD { get { return _cud; } }
private int Consecutive { get { return _consecutive; } }
public DateTime Date { get { return _date; } }
public int Client { get; set; }
public int Employee { get { return _employee; } }
public float NetAmount
{
get
{
float acum = 0;
//Sum (qty * price) of products in a struct collection
}
}
public float GrossAmount
{
get
{
float acum = 0;
//Sum in acum (qty * price + tax) of each products in a struct collection
return acum;
}
}
public float Paid
{
get
{
float acum = 0;
//Sum every paid in a struct collection
return acum;
}
}
public float Change
{ get; set; }
public bool FullPaid
{
get { return (Paid != null && Paid >= NetAmount); }
}
public ArticlesCollection Products { get; set; } //struct previusly declared
public PaidsCollection Paids { get; set; } // struct previously declared
public AuditRegistry(string CUD, int Employee, int Consecutive, DateTime Date, int Client, int C, int Company, int Terminal )
{
this._cud = CUD;
this._employee = Employee;
this._consecutive = Consecutive;
this._date = Date;
this.Client = Client;
base._c = C;
base._company = Company;
base._terminal = Terminal;
}
}
class Order : AuditRegistry
{
int _consec;
public DateTime DeliveryDate { get; set; }
public int Consecutive { get { return _consec; } }
public char Modification { get; set; }
public string Code { get { return (_consec.ToString() + Modificacion); } }
public bool Entregado { get; set; }
/// <summary>
/// Constructor for load a Order from database to memory
/// </summary>
public Order(DateTime DeliveryDate, int Consecutive, char Modification, AuditRegistry Registry) // Here is the child constructor
{
this.DeliveryDate = DeliveryDate;
this._consec = Consecutive;
this.Modification = Modification;
base = AuditRegistry; //Wrong idea
}
/// <summary>
/// Constructor for new Order
/// </summary>
public Pedido(DateTime DeliveryDate, int Employee)
{
this.DeliveryDate = DeliveryDate;
this._consec = 1;
this.Modification = 'A';
base._employee = Employee;
base._date = DateTime.Now;
}
}
Semantics of a child being a father aside...
A good way is using a copy constructor:
class Father
{
int prop1;
int prop2;
// much more properties;
protected Father(Father copy)
{
prop1 = copy.prop1;
prop2 = copy.prop2;
}
}
class Child : Father
{
string _name;
int _age;
//etc...
public Child(string Name, int Age, Father father)
: base(father)
{
this._name = Name;
this._age = Age;
}
}
Its a protected constructor so only children of the parent class can call it. You use the constructor chaining base(father) to intantiate the construtor of the base class and pass the object you want to copy.
You can't assign the base object directly in code, its just a reference to the instance of the base class that the current class derives from.
There is absolutely no way to do this. A Child is a Father and you can't just swap part of the object out to another reference. The base keyword is only intended for calling base class methods explicitly.
Given that a Child is not a "type of" Father, inheritance is probably the wrong answer here anyways. You would be better off doing something like:
class Person
class Father : Person
class Child : Person
{
Father father;
}
(Pseudo-code above). Basically, prefer composition over inheritance here.
Related
public void sortByType(){}
what should i enter here if i have three types of customers different in the way they pay
I have a class customer that inhereted 3 other classes they have a name ,id ,balance and a name of the books array and the date of barrowing and returning how can i sort them by
types??
class Book
{
public string BName { get;set; }
public string Day { get;set; }
public string Month { get;set;} }
public string Year { get;set;} }
public override string ToString(){}
}
then I created an abstract class Customer
abstract class Customer
{
protected string name;
protected double balance;
protected double ID_num;
protected Book[] rental_books = new Book[3];
public string Name { get { return name; } set { name = value; } }
public double Balance { get { return balance; } set { balance = value; } }
public double ID_NUM { get { return ID_num; } set { ID_num = value; } }
public override string ToString() {}
public abstract void BarrowBook(string bn, string d, string m, string y);
public abstract void ReturnBook(string bn, string d, string m, string y);
public abstract void AddToBalance(double sum);
}
and inherted it to the other three child classes and add what I need to each method
class NormalCustomer : Customer{}
class MemberCustomer : Customer{}
class StudentCustomer : Customer{}
then I created a library class
class Library
{
private Customer[] customers;
private int MaxCust=0;
private int count = 0;
public Library(int MaxCust) { this.MaxCust = MaxCust; }
public void Add(Customer c) { customers[count++] = c; }
public void ToString() {
public void SortByBalance()
{
double hold;
for (int i = 0; i < customers.Length - 1; i++)
for (int k = 0; k < (customers.Length - 1) - i; k++)
{
if (customers[k].Balance > customers[k + 1].Balance)
{
hold = customers[k].Balance;
customers[k].Balance = customers[k + 1].Balance;
customers[k + 1].Balance = hold;
}
}
}
}
so all i need now is the methode i mentioned above and how to creat it
let's take your classes
public class Customer { ... }
public class NormalCustomer : Customer{}
public class MemberCustomer : Customer{}
public class StudentCustomer : Customer{}
Providing an array which contains all the children in a mixed order:
Customer [] array = new Customer[]
{
new StudentCustomer(),
new MemberCustomer(),
new NormalCustomer(),
new MemberCustomer(),
new StudentCustomer(),
new StudentCustomer(),
new NormalCustomer(),
};
You can use the method: OfType to extract the individual types:
var children_1 = array.OfType<NormalCustomer>();
var children_2 = array.OfType<MemberCustomer>();
var children_3 = array.OfType<StudentCustomer>();
Now you simply need to concatenate them into a single collection using the Concat method. It expects that the second collection contains the same type of elements so you need to cast it temporarily to the parent type:
Customer [] sorted children_1.Cast<Customer>().Concat(children_2).Concat(children_3).ToArray();
I have the following code:
public interface BaseInterface
{
int ID { get; }
}
public interface SpecialInterface1 : BaseInterface
{
int price { get; }
}
public interface SpecialInterface1 : BaseInterface
{
int xyz { get; }
}
public class Implementation1 : SpecialInterface
{
int price { get; }
int ID { get; internal set; }
}
public class Implementation2 : SpecialInterface
{
int xyz { get; }
int ID { get; internal set; }
}
Now in a Management class I want to add the objects that implement BaseInterface into a List.
I know that I can use as or is to cast the interface to an implementation, but in my project, I have about 10 special interfaces with an implementation each so I would have to write a really big if statements.
public void Add(BaseInterface u, int id)
{
if (u is Implementation1)
{
((Implementation1)u).ID = id;
Units.Add(u);
}
if (u is Implementation2)
{
((Implementation2)u).ID = id;
Units.Add(u);
}
}
My goal is that the id is not changeable outside the implementation and I would provide only the interfaces outside my dll so none can change the id.
A solution would be to add an extra interface. This eliminates the internal setter in your implementation.
internal interface IChangeID
{
void SetID(int id);
}
public interface IBaseInterface
{
int ID { get; }
}
public class Implementation : IBaseInterface,
IChangeID
{
public void SetID(int id) { ID = id; }
public int ID { get; private set; }
}
Only the real implementations should implement IChangeID. Returning IBaseInterface or ISpecialInterface will hide the setter, because those interfaces do not inherit from IChangeID.
This would change your add into:
public void Add(BaseInterface u, int id)
{
((IChangeID)u).SetID(id);
Units.Add(u);
}
If you do want to return the concrete types, not interfaces. You could implement the given interface explicit. This will hide the set method even from the concrete implementation.
public class Implementation : IBaseInterface,
IChangeID
{
void IChangeID.SetID(int id) { ID = id; }
public int ID { get; private set; }
}
var obj = new Implementation();
obj.SetID() // This WILL NOT Compile
If you don't want to modify the interfaces and implementations, you could use C# 7's pattern matching to access the implementation type without casting. It requires 3 lines per implementation type but avoids modifying the classes:
public void Add(BaseInterface u, int id)
{
switch(u)
{
case Implementation1 u1:
u1.ID = id;
break;
case Implementation2 u1:
u1.ID = id;
break;
default :
throw new ArgumentException("Unexpected implementation!");
}
Units.Add(u);
}
The obvious disadvantage is that the code will have to be modified if a new implementation is added.
Another option is to use dynamic, losing type safety. This will fail at runtime if some implementation doesn't have a setter (eg because it was replaced by constructor initialization)
public void Add(BaseInterface u, int id)
{
dynamic x =u;
x.ID=id;
Units.Add(x);
}
While I like this answer the best,
I recommend making the ID a required parameter of all the implementation's constructors, and then to use a factory pattern to generate any instance you require. This makes any instance without the ID set throw an exception at compile time rather than runtime reducing the probability of exceptions.
Here is a simple example that gets you what you want without an additional interface. Should you choose you can combine my answer with #Iqon's answer.
public interface IInterface
{
int ID { get; }
}
internal class InternalImplementation: IInterface {
public InternalImplementation(int ID) { this.ID = ID; }
public int ID { get; set; }
}
public class MyImplementationFactoryService {
public IInterface Create() {
int id = 1 // Or however you get your ID, possibly from a DB query?
return new InternalImplementation(id);
}
public IInterface Create(type|enum createtype) {
// return type based on typeof or enum
}
}
In case you want to use reflection to set property, code below may help
public interface IBaseInterface
{
int ID { get; }
}
public class Impl1 : IBaseInterface
{
public int ID { get; internal set; }
public int Price {get; set;}
}
public class Impl2 : IBaseInterface
{
public int ID { get { return 0;} }
public int Subscription {get; set;}
}
public class Program
{
public static void Main(string[] args)
{
IBaseInterface obj1 = new Impl1();
SetProperty(obj1, "ID", 100);
Console.WriteLine("Object1 Id is {0}", obj1.ID);
IBaseInterface obj2 = new Impl2();
SetProperty(obj2, "ID", 500);
Console.WriteLine("Object2 Id is {0}", obj2.ID);
}
private static void SetProperty(IBaseInterface obj, string propertyName, object id){
if(obj.GetType().GetProperty(propertyName).CanWrite) {
obj.GetType().GetProperty(propertyName).SetValue(obj, id);
Console.WriteLine("CanWrite property '{0}' : {1}" , propertyName, obj.GetType().GetProperty(propertyName).CanWrite);
}
}
}
Output
CanWrite property 'ID' : True
Object1 Id is 100
Object2 Id is 0
Create three small classes unrelated by inheritance—classes Building, Car and Bicycle. Write an interface ICarbonFootprint with a GetCarbonFootprint method. Have each of your classes implement that interface, so that its GetCarbonFootprint method calculates an appropriate carbon footprint for that class (check out a few websites that explain how to calculate carbon footprints). Write an app that creates objects of each of the three classes, places references to those objects in List, then iterates through the List, polymorphically invoking each object’s GetCarbonFootprint method. Constructor of Car initialize “gallon of gas”, and the Building constructor will initialize buiding-square-footage.
how to calculate carbon-footprint
One gallon of gas yields 20 pounds of CO2 for a car
Multiply the square footage by 50 for a building
None for a bicycle
My instructor's code:
public static void Main(string[] args)
{
ICarbonFootprint[] list = new ICarbonFootprint[3];
// add elements to list
list[0] = new Bicycle();
list[1] = new Building(2500);
list[2] = new Car(10);
// display carbon footprint of each object
for (int i = 0; i < list.Length; i++)
list[i].GetCarbonFootprint();
} // end Main
}
My code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Miller
{
class Program
{
static void Main(string[] args)
{
Bicycle bike = new Bicycle();
Building b = new Building();
Car car = new Car();
List<ICarbonFootprint> list = new List<ICarbonFootprint>();
list.Add(bike);
list.Add(b);
list.Add(car);
int totalCarbon = 0;
foreach (var item in list)
{
totalCarbon += item.GetCarbonFootprint();
Console.WriteLine("{0} has a footprint of: {1}", item, item.GetCarbonFootprint());
}
Console.WriteLine("Total footprint is: {0}", totalCarbon);
Console.ReadKey();
}
}
public class Bicycle : ICarbonFootprint
{
private string _make;
private string _model;
public string Make
{
get { return _make; }
set { _make = value; }
}
public string Model
{
get { return _model; }
set { _model = value; }
}
public int GetCarbonFootprint()
{
return 10;
}
public override string ToString()
{
return string.Format("Bike");
}
}
public class Building : ICarbonFootprint
{
private string _address;
public string Address
{
get { return _address; }
set { _address = value; }
}
public int GetCarbonFootprint()
{
return 2000;
}
public override string ToString()
{
return string.Format("Building");
}
}
public class Car : ICarbonFootprint
{
private string _make;
private string _model;
public string Make
{
get { return _make; }
set { _make = value; }
}
public string Model
{
get { return _model; }
set { _model = value; }
}
public int GetCarbonFootprint()
{
return 1500;
}
public override string ToString()
{
return string.Format("Car");
}
}
public interface ICarbonFootprint
{
int GetCarbonFootprint();
}
}
Me integrating my instructor's code (lines 12-23 changed AKA class Program was the only thing changed):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Miller
{
class Program
{
public static void Main(string[] args)
{
ICarbonFootprint[] list = new ICarbonFootprint[3];
// add elements to list
list[0] = new Bicycle();
list[1] = new Building(2500);
list[2] = new Car(10);
// display carbon footprint of each object
for (int i = 0; i < list.Length; i++)
list[i].GetCarbonFootprint();
} // end Main
}
public class Bicycle : ICarbonFootprint
{
private string _make;
private string _model;
public string Make
{
get { return _make; }
set { _make = value; }
}
public string Model
{
get { return _model; }
set { _model = value; }
}
public int GetCarbonFootprint()
{
return 10;
}
public override string ToString()
{
return string.Format("Bike");
}
}
public class Building : ICarbonFootprint
{
private string _address;
public string Address
{
get { return _address; }
set { _address = value; }
}
public int GetCarbonFootprint()
{
return 2000;
}
public override string ToString()
{
return string.Format("Building");
}
}
public class Car : ICarbonFootprint
{
private string _make;
private string _model;
public string Make
{
get { return _make; }
set { _make = value; }
}
public string Model
{
get { return _model; }
set { _model = value; }
}
public int GetCarbonFootprint()
{
return 1500;
}
public override string ToString()
{
return string.Format("Car");
}
}
public interface ICarbonFootprint
{
int GetCarbonFootprint();
}
}
So, replacing my code for class Program with my instructor's code, I received the following errors:
Program.cs(51,23,51,41): error CS1729: 'Miller.Building' does not contain a constructor that takes 1 arguments
Program.cs(52,23,52,34): error CS1729: 'Miller.Car' does not contain a constructor that takes 1 arguments
Now, because the last two days before Spring break were cancelled due to the weather (snow), we weren't able to discuss. My code seems to do what the directions ask, but I would like to get my instructor's code for class Program working with my code. Could someone help me with these errors possibly?
There are a few issues with your code.
First up you need to include the constructors to make the code compile.
For Building this would look like:
private int squareFootage;
public Building(int squareFootage)
{
this.squareFootage = squareFootage;
}
And for Car this would look like:
private int gasGallons;
public Car(int gasGallons)
{
this.gasGallons = gasGallons;
}
Next, you're not following the rules for calculating the carbon footprint.
They should be:
//Bicycle
public int GetCarbonFootprint()
{
return 0;
}
//Building
public int GetCarbonFootprint()
{
return 50 * squareFootage;
}
//Car
public int GetCarbonFootprint()
{
return 20 * gasGallons;
}
Finally, your instructor's code doesn't actually display any results. The code in the for loop should be changed to be Console.WriteLine(list[i].GetCarbonFootprint()); if this is a console app.
So, all up the code should look like this:
public static void Main(string[] args)
{
ICarbonFootprint[] list = new ICarbonFootprint[3];
// add elements to list
list[0] = new Bicycle();
list[1] = new Building(2500);
list[2] = new Car(10);
// display carbon footprint of each object
for (int i = 0; i < list.Length; i++)
Console.WriteLine(list[i].GetCarbonFootprint());
}
public class Bicycle : ICarbonFootprint
{
public string Make { get; set; }
public string Model { get; set; }
public int GetCarbonFootprint()
{
return 0;
}
}
public class Building : ICarbonFootprint
{
private int squareFootage;
public Building(int squareFootage)
{
this.squareFootage = squareFootage;
}
public string Address { get; set; }
public int GetCarbonFootprint()
{
return 50 * squareFootage;
}
}
public class Car : ICarbonFootprint
{
private int gasGallons;
public Car(int gasGallons)
{
this.gasGallons = gasGallons;
}
public string Make { get; set; }
public string Model { get; set; }
public int GetCarbonFootprint()
{
return 20 * gasGallons;
}
}
public interface ICarbonFootprint
{
int GetCarbonFootprint();
}
I've opted to short-cut the property definitions rather than implement them with fields.
The output is:
0
125000
200
You should write constructors for Building and Car like next:
public Building(int MyValue)
{
...
}
and your code will work fine.
Suggestion: Car and Bicycle shares properties, and the ICarbonFootprint implementation, so you can create a base class with an abstract method. Also the GetCarbonFootprint from ICarbonFootprint interface must be type of System.Double.
public interface ICarbonFootprint
{
int GetCarbonFootprint();
}
public class Building : ICarbonFootprint
{
public int BuildingSquareFootage { get; set; }
public string Address { get; set; }
public Building(int buildingSquareFootage, string address)
{
BuildingSquareFootage = buildingSquareFootage;
Address = address;
}
public int GetCarbonFootprint()
{
return BuildingSquareFootage * 50;
}
public override string ToString()
{
return string.Format("Building");
}
}
public abstract class CarBicycleBase : ICarbonFootprint
{
public string Make { get; set; }
public string Model { get; set; }
protected CarBicycleBase(string make, string model)
{
Make = make;
Model = model;
}
public abstract int GetCarbonFootprint();
}
public class Bicycle : CarBicycleBase
{
public Bicycle(string make, string model)
: base(make, model) { }
public override int GetCarbonFootprint()
{
return 0;
}
public override string ToString()
{
return string.Format("Bike");
}
}
public class Car : CarBicycleBase
{
public int GallonOfGas { get; set; }
public Car(int gallonOfGas, string make, string model)
: base(make, model)
{
GallonOfGas = gallonOfGas;
}
public override int GetCarbonFootprint()
{
return GallonOfGas * 20;
}
public override string ToString()
{
return string.Format("Car");
}
}
Example:
...
var list = new List<ICarbonFootprint>(3)
{
new Car(10, "...", "..."),
new Bicycle("...", "..."),
new Building(20, "...")
};
foreach (ICarbonFootprint item in list)
item.GetCarbonFootprint();
...
I hope it helps.
I am trying to implement a system that can handle multiple discounts applied to my cart/completed orders. I have applied a strategy type pattern to encapsulate the processing of the discounts within the discounts.
I have come up with the following: an abstract discount base class with subclasses making up the concrete discounts. These are then applied to either an order/cart object and will process the contents of the order/cart when added to the cart/order.
Would love some comments on the code attached. Various protected constructors and members marked "virtual" needed for nhibernate.
Chev
using System;
using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
namespace CodeCollective.RaceFace.DiscountEngine
{
[TestFixture]
public class TestAll
{
#region Tests
[Test]
public void Can_Add_Items_To_Cart()
{
Cart cart = LoadCart();
// display the cart contents
foreach (LineItem lineItem in cart.LineItems)
{
Console.WriteLine("Product: {0}\t Price: {1:c}\t Quantity: {2} \t Subtotal: {4:c} \t Discount: {3:c} \t| Discounts Applied: {5}", lineItem.Product.Name, lineItem.Product.Price, lineItem.Quantity, lineItem.DiscountAmount, lineItem.Subtotal, lineItem.Discounts.Count);
}
}
[Test]
public void Can_Add_Items_To_An_Order()
{
// create the cart
Order order = new Order(new Member("Chev"));
// add items to the cart
GenericProduct hat = new GenericProduct("Cap", 110m);
order.AddLineItem(hat, 5);
EventItem race = new EventItem("Ticket", 90m);
order.AddLineItem(race, 1);
// add discounts
Discount percentageOff = new PercentageOffDiscount("10% off all items", 0.10m);
percentageOff.CanBeUsedInJuntionWithOtherDiscounts = false;
order.AddDiscount(percentageOff);
Discount spendXgetY = new SpendMoreThanXGetYDiscount("Spend more than R100 get 10% off", 100m, 0.1m);
spendXgetY.SupercedesOtherDiscounts = true;
order.AddDiscount(spendXgetY);
Discount buyXGetY = new BuyXGetYFree("Buy 4 hats get 2 hat free", new List<Product> { hat }, 4, 2);
buyXGetY.CanBeUsedInJuntionWithOtherDiscounts = false;
buyXGetY.SupercedesOtherDiscounts = true;
order.AddDiscount(buyXGetY);
// display the cart contents
foreach (LineItem lineItem in order.LineItems)
{
Console.WriteLine("Product: {0}\t Price: {1:c}\t Quantity: {2} \t Subtotal: {4:c} \t Discount: {3:c} \t| Discounts Applied: {5}", lineItem.Product.Name, lineItem.Product.Price, lineItem.Quantity, lineItem.DiscountAmount, lineItem.Subtotal, lineItem.Discounts.Count);
}
}
[Test]
public void Can_Process_A_Cart_Into_An_Order()
{
Cart cart = LoadCart();
Order order = ProcessCartToOrder(cart);
// display the cart contents
foreach (LineItem lineItem in order.LineItems)
{
Console.WriteLine("Product: {0}\t Price: {1:c}\t Quantity: {2} \t Subtotal: {4:c} \t Discount: {3:c} \t| Discounts Applied: {5}", lineItem.Product.Name, lineItem.Product.Price, lineItem.Quantity, lineItem.DiscountAmount, lineItem.Subtotal, lineItem.Discounts.Count);
}
}
private static Cart LoadCart()
{
// create the cart
Cart cart = new Cart(new Member("Chev"));
// add items to the cart
GenericProduct hat = new GenericProduct("Cap", 110m);
cart.AddLineItem(hat, 5);
EventItem race = new EventItem("Ticket", 90m);
cart.AddLineItem(race, 1);
// add discounts
Discount percentageOff = new PercentageOffDiscount("10% off all items", 0.10m);
percentageOff.CanBeUsedInJuntionWithOtherDiscounts = false;
cart.AddDiscount(percentageOff);
Discount spendXgetY = new SpendMoreThanXGetYDiscount("Spend more than R100 get 10% off", 100m, 0.1m);
spendXgetY.SupercedesOtherDiscounts = true;
cart.AddDiscount(spendXgetY);
Discount buyXGetY = new BuyXGetYFree("Buy 4 hats get 2 hat free", new List<Product> { hat }, 4, 2);
buyXGetY.CanBeUsedInJuntionWithOtherDiscounts = false;
buyXGetY.SupercedesOtherDiscounts = true;
cart.AddDiscount(buyXGetY);
return cart;
}
private static Order ProcessCartToOrder(Cart cart)
{
Order order = new Order(cart.Member);
foreach(LineItem lineItem in cart.LineItems)
{
order.AddLineItem(lineItem.Product, lineItem.Quantity);
foreach(Discount discount in lineItem.Discounts)
{
order.AddDiscount(discount);
}
}
return order;
}
#endregion
}
#region Discounts
[Serializable]
public abstract class Discount : EntityBase
{
protected internal Discount()
{
}
public Discount(string name)
{
Name = name;
}
public virtual bool CanBeUsedInJuntionWithOtherDiscounts { get; set; }
public virtual bool SupercedesOtherDiscounts { get; set; }
public abstract OrderBase ApplyDiscount();
public virtual OrderBase OrderBase { get; set; }
public virtual string Name { get; private set; }
}
[Serializable]
public class PercentageOffDiscount : Discount
{
protected internal PercentageOffDiscount()
{
}
public PercentageOffDiscount(string name, decimal discountPercentage)
: base(name)
{
DiscountPercentage = discountPercentage;
}
public override OrderBase ApplyDiscount()
{
// custom processing
foreach (LineItem lineItem in OrderBase.LineItems)
{
lineItem.DiscountAmount = lineItem.Product.Price * DiscountPercentage;
lineItem.AddDiscount(this);
}
return OrderBase;
}
public virtual decimal DiscountPercentage { get; set; }
}
[Serializable]
public class BuyXGetYFree : Discount
{
protected internal BuyXGetYFree()
{
}
public BuyXGetYFree(string name, IList<Product> applicableProducts, int x, int y)
: base(name)
{
ApplicableProducts = applicableProducts;
X = x;
Y = y;
}
public override OrderBase ApplyDiscount()
{
// custom processing
foreach (LineItem lineItem in OrderBase.LineItems)
{
if(ApplicableProducts.Contains(lineItem.Product) && lineItem.Quantity > X)
{
lineItem.DiscountAmount += ((lineItem.Quantity / X) * Y) * lineItem.Product.Price;
lineItem.AddDiscount(this);
}
}
return OrderBase;
}
public virtual IList<Product> ApplicableProducts { get; set; }
public virtual int X { get; set; }
public virtual int Y { get; set; }
}
[Serializable]
public class SpendMoreThanXGetYDiscount : Discount
{
protected internal SpendMoreThanXGetYDiscount()
{
}
public SpendMoreThanXGetYDiscount(string name, decimal threshold, decimal discountPercentage)
: base(name)
{
Threshold = threshold;
DiscountPercentage = discountPercentage;
}
public override OrderBase ApplyDiscount()
{
// if the total for the cart/order is more than x apply discount
if(OrderBase.GrossTotal > Threshold)
{
// custom processing
foreach (LineItem lineItem in OrderBase.LineItems)
{
lineItem.DiscountAmount += lineItem.Product.Price * DiscountPercentage;
lineItem.AddDiscount(this);
}
}
return OrderBase;
}
public virtual decimal Threshold { get; set; }
public virtual decimal DiscountPercentage { get; set; }
}
#endregion
#region Order
[Serializable]
public abstract class OrderBase : EntityBase
{
private IList<LineItem> _LineItems = new List<LineItem>();
private IList<Discount> _Discounts = new List<Discount>();
protected internal OrderBase() { }
protected OrderBase(Member member)
{
Member = member;
DateCreated = DateTime.Now;
}
public virtual Member Member { get; set; }
public LineItem AddLineItem(Product product, int quantity)
{
LineItem lineItem = new LineItem(this, product, quantity);
_LineItems.Add(lineItem);
return lineItem;
}
public void AddDiscount(Discount discount)
{
discount.OrderBase = this;
discount.ApplyDiscount();
_Discounts.Add(discount);
}
public virtual decimal GrossTotal
{
get
{
return LineItems
.Sum(x => x.Product.Price * x.Quantity);
}
}
public virtual DateTime DateCreated { get; private set; }
public IList<LineItem> LineItems
{
get
{
return _LineItems;
}
}
}
[Serializable]
public class Order : OrderBase
{
protected internal Order() { }
public Order(Member member)
: base(member)
{
}
}
#endregion
#region LineItems
[Serializable]
public class LineItem : EntityBase
{
private IList<Discount> _Discounts = new List<Discount>();
protected internal LineItem() { }
public LineItem(OrderBase order, Product product, int quantity)
{
Order = order;
Product = product;
Quantity = quantity;
}
public virtual void AddDiscount(Discount discount)
{
_Discounts.Add(discount);
}
public virtual OrderBase Order { get; private set; }
public virtual Product Product { get; private set; }
public virtual int Quantity { get; private set; }
public virtual decimal DiscountAmount { get; set; }
public virtual decimal Subtotal
{
get { return (Product.Price*Quantity) - DiscountAmount; }
}
public virtual IList<Discount> Discounts
{
get { return _Discounts.ToList().AsReadOnly(); }
}
}
#endregion
#region Member
[Serializable]
public class Member : EntityBase
{
protected internal Member() { }
public Member(string name)
{
Name = name;
}
public virtual string Name { get; set; }
}
#endregion
#region Cart
[Serializable]
public class Cart : OrderBase
{
protected internal Cart()
{
}
public Cart(Member member)
: base(member)
{
}
}
#endregion
#region Products
[Serializable]
public abstract class Product : EntityBase
{
protected internal Product()
{
}
public Product(string name, decimal price)
{
Name = name;
Price = price;
}
public virtual string Name { get; set; }
public virtual decimal Price { get; set; }
}
// generic product used in most situations for simple products
[Serializable]
public class GenericProduct : Product
{
protected internal GenericProduct()
{
}
public GenericProduct(String name, Decimal price) : base(name, price)
{
}
}
// custom product with additional properties and methods
[Serializable]
public class EventItem : Product
{
protected internal EventItem()
{
}
public EventItem(string name, decimal price) : base(name, price)
{
}
}
#endregion
#region EntityBase
[Serializable]
public abstract class EntityBase
{
private readonly Guid _id;
protected EntityBase() : this(GenerateGuidComb())
{
}
protected EntityBase(Guid id)
{
_id = id;
}
public virtual Guid Id
{
get { return _id; }
}
private static Guid GenerateGuidComb()
{
var destinationArray = Guid.NewGuid().ToByteArray();
var time = new DateTime(0x76c, 1, 1);
var now = DateTime.Now;
var span = new TimeSpan(now.Ticks - time.Ticks);
var timeOfDay = now.TimeOfDay;
var bytes = BitConverter.GetBytes(span.Days);
var array = BitConverter.GetBytes((long)(timeOfDay.TotalMilliseconds / 3.333333));
Array.Reverse(bytes);
Array.Reverse(array);
Array.Copy(bytes, bytes.Length - 2, destinationArray, destinationArray.Length - 6, 2);
Array.Copy(array, array.Length - 4, destinationArray, destinationArray.Length - 4, 4);
return new Guid(destinationArray);
}
public virtual int Version { get; protected set; }
#region Equality Tests
public override bool Equals(object entity)
{
return entity != null
&& entity is EntityBase
&& this == (EntityBase)entity;
}
public static bool operator ==(EntityBase base1,
EntityBase base2)
{
// check for both null (cast to object or recursive loop)
if ((object)base1 == null && (object)base2 == null)
{
return true;
}
// check for either of them == to null
if ((object)base1 == null || (object)base2 == null)
{
return false;
}
if (base1.Id != base2.Id)
{
return false;
}
return true;
}
public static bool operator !=(EntityBase base1, EntityBase base2)
{
return (!(base1 == base2));
}
public override int GetHashCode()
{
{
return Id.GetHashCode();
}
}
#endregion
#endregion
}
}
As I mentioned in the comments to your question I don't think strategy is apt in this case.
To me all these discounts BuyXGetYFree, SpendMoreThanXGetYDiscount etc are all rules (and may not all neccesarily be about getting discount) that can be applied in calculating product/cart cost. I would build a RulesEngine utilising the rules you outlined and when you ask the cart to calculate its cost process it against the RulesEngine. The RulesEngine would process the product lines making up the cart and the overall order and apply the relevant adjustments to costs etc.
The RulesEngine could even control the order in which the rules are applied.
Rules could be product based (e.g. Buy one get one free) or order based (eg. Buy X items get free shipping) and you could even have expiry dates built in. These rules would be persisted to a data store.
To me the Decorator pattern seems more applicable here. It starts with the a similar Discount class hierarchy you have, but the discounts would also implement OrderBase. Then they decorate the order instead of just being attached to it. When queried, the decorator gets the order data from the order instance it decorates (which may be a plain vanilla order, or another decorator), and applies to it the appropriate discount. IMO this is fairly easy to implement but also flexible enough; in short, to me this is the simplest solution that may work.
The order of discounts in the decorator chain is probably not arbitrary though; at first guess you should apply price altering discounts first, then quantity altering ones. But I guess this is not a very strong constraint.
Just found LinFu - looks very impressive, but I can't quite see how to do what I want to do - which is multiple inheritance by mixin (composition/delegation as I'd say in my VB5/6 days - when I had a tool to generate the tedious repetitive delegation code - it was whilst looking for a C# equivalent that I found LinFu).
FURTHER EDIT: TO clarify what I mean by composition/delegation and mixin.
public class Person : NEOtherBase, IName, IAge
{
public Person()
{
}
public Person(string name, int age)
{
Name = name;
Age = age;
}
//Name "Mixin" - you'd need this code in any object that wanted to
//use the NameObject to implement IName
private NameObject _nameObj = new NameObject();
public string Name
{
get { return _nameObj.Name; }
set { _nameObj.Name = value; }
}
//--------------------
//Age "Mixin" you'd need this code in any object that wanted to
//use the AgeObject to implement IAge
private AgeObject _ageObj = new AgeObject();
public int Age
{
get { return _ageObj.Age; }
set { _ageObj.Age = value; }
}
//------------------
}
public interface IName
{
string Name { get; set; }
}
public class NameObject : IName
{
public NameObject()
{}
public NameObject(string name)
{
_name = name;
}
private string _name;
public string Name { get { return _name; } set { _name = value; } }
}
public interface IAge
{
int Age { get; set; }
}
public class AgeObject : IAge
{
public AgeObject()
{}
public AgeObject(int age)
{
_age = age;
}
private int _age;
public int Age { get { return _age; } set { _age = value; } }
}
Imagine objects with many more properties, used in many more "subclasses" and you start to see the tedium. A code-gernation tool would actually be just fine...
So, LinFu....
The mixin example below is fine but I'd want to have an actual Person class (as above) - what's the LinFu-esque way of doing that? Or have I missed the whole point?
EDIT: I need to be able to do this with classes that are already subclassed.
DynamicObject dynamic = new DynamicObject();
IPerson person = null;
// This will return false
bool isPerson = dynamic.LooksLike<IPerson>();
// Implement IPerson
dynamic.MixWith(new HasAge(18));
dynamic.MixWith(new Nameable("Me"));
// Now that it’s implemented, this
// will be true
isPerson = dynamic.LooksLike<IPerson>();
if (isPerson)
person = dynamic.CreateDuck<IPerson>();
// This will return “Me”
string name = person.Name;
// This will return ‘18’
int age = person.Age;