C# Decorators - Interfaces or Abstract Classes? -
this thread, decorator pattern implementation, has implementation of decorator using abstract classes. don't simple fact condimentdecorator not beverage in implementation given there. i'd use interfaces instead. aren't abstract classes better is-a relationships, , interfaces better has-a relationships?
public interface ibeverage { // description of beverage string description { get; } // calculate cost of beverage double cost { get; } } // houseblend coffee implements ibeverage public class houseblend : ibeverage { private string description; public string description { { return description; } } private double cost; public double cost { { return cost; } } // constructor public houseblend() { description = "house blend"; cost = 0.89; } } // darkroast coffee implements ibeverage public class darkroast : ibeverage { private string description; public string description { { return description; } } private double cost; public double cost { { return cost; } } // constructor public darkroast() { description = "dark roast"; cost = 1.10; } } // mocha decorator public class mocha { // mocha has-a beverage private ibeverage m_beverage; private string description; public string description { { return description; } } private public double cost { { return cost; } } // constructor binds object passed member var public mocha(ibeverage beverage) { m_beverage = beverage; // not necessary purpose of example description = m_beverage.description + ", mocha"; cost = 0.20 + m_beverage.cost; } } use this: mocha mhb = new mocha(new houseblend()); // house blend mocha flavor
both base clases , interfaces used model is-a relationships. interface simple idisposable can understood "is object manually controlled lifecycle", "disposable". more tangible differences in whether base implementation or data fields allowed; , in ability combine multiple hierarchies.
now, when implementing any pattern, have enough information see whether need data fields or not. however, hardly ever able rule out future need involve same classes in additional patterns software grows. perspective, general preference of interfaces on abstract classes gives more long term flexibility - whenever have choice.
by nature of decorator, have choice. components typically not have predefined order of how should nest. if did, use inheritance directly, instead of components. should prefer interfaces compose decorator.
all said, original argument valid well. decorator components (features) can understood is-a relationships if like; not natural way of looking @ them.
Comments
Post a Comment