CS 342 - 3/29/16 Design Patterns - Result of research into code re-use "Gang of Four" Book Design Patterns: Elements of Reusable Object-Oriented Software by Erich Gamma, Richard Helm, Ralph Johnson and John Vlisses - Describes 23 Design patterns Adaptor Design Pattern Two sections of code that were developed separately that now need to work together. Client Class Adaptor Class Vendor Class Assume we have a method that uses the Duck class public void methodX ( Duck d ) { ... d.quack(); ... d.fly(); ... } // original code uses the Duck interface Duck d1 = new MallardDuck(); methodX (d1); // we want to call methodX with a parameter of Turkey Turkey t1 = new WildTurkey(); methodX (t1); // this would fail // but the following will succeed!! Duck td1 = new TurkeyAdaptor ( t1 ); methodX ( td1 ); The basics of the Adaptor Design Pattern is the create a wrapper class for the "turkey" class class TurkeyAdaptor implements Duck { private Turkey t; public TurkeyAdaptor ( Tuckey tparam ) { t = tparam; } public void quack () { t.gobble(); } public void fly() { for (int i = 0 ; i < 5 ; i++) t.fly(); } } Singleton - When only one instance of a class is ever created. - Often occurs with a GUI - Also used with shared data class Singleton { private static Singleton instance = null; private int sharedValue1; private int sharedValue2; private Singleton() { ... } public static synchronized Singleton getInstance() { if (instance == null) instance = new Singleton(); return instance; } ... public void doSomething() { ... } }