class MainApp { public static void Main(String []a){ // Constructor is protected -- cannot use new Singleton s1 = Singleton.getInstance(); Singleton s2 = Singleton.getInstance(); // Test for same instance if (s1 == s2){ // true - Objects are the same instance } } }
class MainApp { static void main() { // Create ConcreteComponent and two Decorators ConcreteComponent c = new ConcreteComponent(); ConcreteDecoratorA d1 = new ConcreteDecoratorA(); ConcreteDecoratorB d2 = new ConcreteDecoratorB(); // Link decorators d1.SetComponent(c); d2.SetComponent(d1); d2.Operation(); } }
vs Inheritance • Both allow you to change how an object behaves • The decorator pattern can be used to make it possible to extend (decorate) the functionality of a certain object at runtime. • Inheritance adds behavior at compilation-time.
WhiteBody body = new WhiteBody(); Mask mask = new Mask(); Helmet helmet = new Helmet(); // Link decorators mask.SetComponent(body); helmet.SetComponent(mask); helmet.Operation();
asu.edu Sum m er 2017 Disclaim er. These slides can only be used as study m aterial for the class C SE360 at ASU. They cannot be distributed or used for another purpose.