design patterns in oo abap

Upload: yakubshah

Post on 13-Oct-2015

182 views

Category:

Documents


13 download

DESCRIPTION

Design Patterns of singleton, Factory and others

TRANSCRIPT

Title of the presentation This is the subtitle

Design Patterns

Savio Sebastian, Patterns Component TeamJanuary 11, 2008

sample for a picture in the title slide

# SAP 2007 / Page 2/104

IntroductionCreational Patterns2.1.Singleton Pattern2.2.Factory Method and Abstract Factory Patterns Structural Patterns3.1.Adapter Pattern3.2.Decorator Pattern3.3. Faade Pattern Behavioral Patterns4.1.Command Pattern4.2.Observer PatternAgendasample for a picture in the divider slide

# SAP 2007 / Page 3What are Design Patterns?Why do we use them?Types of Design PatternsWhat Patterns is NOT!Introduction

# SAP 2007 / Page 4Introduction to Design PatternsWhat? Template for writing codePatterns use OO Design PrinciplesConcepts like abstraction, inheritance, polymorphismWhy?Readability familiarityMaintenanceSpeed tested, proven development paradigmsCommunication shared vocabularyUI Patterns WHY?InterviewsThis is a refresher infosessions #Types of Design Patterns SAP 2007 / Page 5 #What Patterns are NOTLibrary of Code?Structure for classes to solve certain problemsBut arent Libraries and Frameworks also Design Patterns?They are specific implementations to which we link our codeThey use Design Patterns to write their Java CodeIs it something to do with s/w architecture? SAP 2007 / Page 6Software ArchitectureDesign PatternsComponent InteractionClass InteractionIncludes Design PatternsFar from it Interface == Abstract ClassWhile we study Design Patterns, Abstract Classes and Interface often mean the same thing. SAP 2007 / Page 7 SAP 2007 / Page 8Singleton PatternFactory Method & Abstract FactoryCreational Patterns

#Singleton Pattern the simplest patternEnsures a class has only one instance, and provides a global point of access to itWhere to use?CachesObjects that handle registry settingsFor LoggingDevice driversPatterns Component Example of Singleton Pattern Usage:IWDComponentUsage componentUsage = patternAccessPoint.getSingleton(IPatternRtApi.TRANSACTION);

SAP 2007 / Page 9Singleton Class DiagramSingleton Classstatic uniqueInstance// other useful Singleton Datastatic getInstance()// other useful Singleton Method SAP 2007 / Page 10Improving performance SAP 2007 / Page 11Create Unique Instance EagerlyCode:public class Singleton {private static Singleton uniqueInstance = new Singleton();// other useful instance variables hereprivate Singleton() {}public static synchronized Singleton getInstance() {return uniqueInstance;}// other useful methods here}This code is guaranteed to be thread-safe! SAP 2007 / Page 12 #Double-Checked LockingCode:// Danger! This implementation of Singleton not guaranteed to work prior to Java 5public class Singleton {private volatile static Singleton uniqueInstance;private Singleton() {}public static Singleton getInstance() {if (uniqueInstance == null) {synchronized (Singleton.class) {if (uniqueInstance == null) {uniqueInstance = new Singleton();}}}return uniqueInstance;}}This is thread-safe again! SAP 2007 / Page 13 #Factory Method PatternCreates objects without specifying the exact class to createMost popular OO Pattern

SAP 2007 / Page 14Compare Two ImplementationsDependent Pizza StorePizza Storepublic class DependentPizzaStore { public Pizza createPizza(String style, String type) { Pizza pizza = null; if (style.equals("NY")) { if (type.equals("cheese")) { pizza = new NYStyleCheesePizza(); } else if (type.equals("veggie")) { pizza = new NYStyleVeggiePizza(); } else if (type.equals("pepperoni")) { pizza = new NYStylePepperoniPizza(); } } else if (style.equals("Chicago")) { if (type.equals("cheese")) { pizza = new ChicagoStyleCheesePizza(); } else if (type.equals("veggie")) { pizza = new ChicagoStyleVeggiePizza(); } else if (type.equals("pepperoni")) { pizza = new ChicagoStylePepperoniPizza(); } } else { System.out.println("Error: invalid type of pizza"); return null; } pizza.prepare(); pizza.bake(); pizza.cut(); pizza.box(); return pizza; }}public abstract class PizzaStore { abstract Pizza createPizza(String item); public Pizza orderPizza(String type) { Pizza pizza = createPizza(type); System.out.println("--- Making a " + pizza.getName() + " ---"); pizza.prepare(); pizza.bake(); pizza.cut(); pizza.box(); return pizza; }}

public class NYPizzaStore extends PizzaStore { Pizza createPizza(String item) { if (item.equals("cheese")) { return new NYStyleCheesePizza(); } else if (item.equals("veggie")) { return new NYStyleVeggiePizza(); } else if (item.equals("clam")) { return new NYStyleClamPizza(); } else if (item.equals("pepperoni")) { return new NYStylePepperoniPizza(); } else return null; }}

SAP 2007 / Page 15Compare DependenciesDependent Pizza StorePizza Store SAP 2007 / Page 16PizzaStoreNYStyleCheesePizzaChicagoStyleCheezePizzaNYStyleVeggiePizzaNYStylePeppoPizzaChicagoStyleVeggiePizzaChicagoStylePeppoPizzaPizzaNYStyleCheesePizzaChicagoStyleCheezePizzaNYStyleVeggiePizzaNYStylePeppoPizzaChicagoStyleVeggiePizzaChicagoStylePeppoPizzaPizzaStoreExplanationsNot using Factory MethodUsing Factory MethodDependent Pizza Store depends on all the available Pizzas.Pizza Store depends only on Abstract Pizza which is implemented by specific PizzasAbstraction Principle violatedDepends only on AbstractionDirection of dependency is downward to the different types of PizzasDifferent types of pizzas implement Pizza inversion of dependencyAddition of a new style of pizzas will require BIG change in codeAdd new California Style Store and the respective Californian Pizzas extending the Pizza classCode needs to be open for modificationCode can be closed for modification, open for extension SAP 2007 / Page 17Class Diagram of Factory Method SAP 2007 / Page 18CreatorfactoryMethod()operations()Concrete CreatorfactoryMethod()ProductConcrete Product #Abstract Factory PatternGroups object factories that have a common themeGroups together a set of related productsUses Composition and InheritanceUses Factory Method to create productsEssentially FACTORY SAP 2007 / Page 19Families Ingredients / PizzasIngredientsPizzaNY Style:Sauce: MarinaraDough: Thin CrustCheese: ReggianoVeggies: Garlic, Onion, MushroomChicago Style:Sauce: TomatoDough: Thick CrustCheese: MozzarellaVeggies: Onion, Mushroom, CapsicumCalifornia Style:Sauce:Dough:Cheese:Veggies:...

Cheese Pizza

Veggie Pizza

Pepperoni Pizza SAP 2007 / Page 20Factory Method versus Abstract FactoryFactory MethodAbstract Factory SAP 2007 / Page 21PizzaNYStyleCheesePizzaChicagoStyleCheezePizzaNYStyleVeggiePizzaNYStylePeppoPizzaChicagoStyleVeggiePizzaChicagoStylePeppoPizzaPizzaStorePizzaCheesePizzaVeggiePizzaPeppoPizzaPizzaStorePizzaIngredientsNYStyleChicagoStyle #Quick Reference: Different Types of Creational PatternsNameDescriptionAbstract factoryProvide an interface for creating families of related or dependent objects without specifying their concrete classes.Factory methodDefine an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.BuilderSeparate the construction of a complex object from its representation so that the same construction process can create different representations.Lazy initializationTactic of delaying the creation of an object, the calculation of a value, or some other expensive process until the first time it is needed.Object PoolAvoid expensive acquisition and release of resources by recycling objects that are no longer in usePrototypeSpecify the kinds of objects to create using a prototypical instance, and create new objects by copying this prototype.SingletonEnsure a class only has one instance, and provide a global point of access to it. SAP 2007 / Page 22 # SAP 2007 / Page 23Adapter PatternDecorator PatternFaade PatternStructural Patterns

#Adapter PatternAdapter lets classes work together that couldn't otherwise because of incompatible interfaces SAP 2007 / Page 24Your Existing SystemAdapter

VendorClassClientTarget Interfacerequest()Adapterrequest()AdaptedspecificRequest()DucksTarget Interfacepublic interface Duck { public void quack(); public void fly();}An implementation the Target Interfacepublic class MallardDuck implements Duck { public void quack() { System.out.println("Quack"); } public void fly() { System.out.println("I'm flying"); }} SAP 2007 / Page 25TurkeysTo-Be-Adapted Interfacepublic interface Turkey { public void gobble(); public void fly();}An implementation of To-Be-Adapted Interfacepublic class WildTurkey implements Turkey { public void gobble() { System.out.println("Gobble gobble"); } public void fly() { System.out.println("I'm flying a short distance"); }} SAP 2007 / Page 26Turkey Adaptedpublic class TurkeyAdapter implements Duck { Turkey turkey; public TurkeyAdapter(Turkey turkey) { this.turkey = turkey; } public void quack() { turkey.gobble(); } public void fly() { for(int i=0; i < 5; i++) { turkey.fly(); } }}

SAP 2007 / Page 27Client Application Test Drivepublic class DuckTestDrive { public static void main(String[] args) { MallardDuck duck = new MallardDuck(); WildTurkey turkey = new WildTurkey(); Duck turkeyAdapter = new TurkeyAdapter(turkey); System.out.println("The Turkey says..."); turkey.gobble(); turkey.fly(); System.out.println("\nThe Duck says..."); testDuck(duck); System.out.println("\nThe TurkeyAdapter says..."); testDuck(turkeyAdapter); } static void testDuck(Duck duck) { duck.quack(); duck.fly(); }} SAP 2007 / Page 28Adapting Enumerations to Iteratorspublic class EnumerationIterator implements Iterator { Enumeration enumeration; public EnumerationIterator(Enumeration enumeration) { this.enumeration = enumeration; } public boolean hasNext() { return enumeration.hasMoreElements(); } public Object next() { return enumeration.nextElement(); } public void remove() { throw new UnsupportedOperationException(); }} SAP 2007 / Page 29Decorator PatternAttach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to sub-classing for extending functionality.Decorators have the same super-type as the objects they decorateYou can use more than one decorators to wrap an object

SAP 2007 / Page 30

Concrete Component we can dynamically add new behaviorEach component can be used on its own, or wrapped by a decoratorConcrete Decorator has an instance variable for the thing it decoratesjava.io uses decorator to extend behaviors

SAP 2007 / Page 31FilterInputStream.javapublic class FilterInputStream extends InputStream { protected volatile InputStream in; protected FilterInputStream(InputStream in) { this.in = in; } public int read() throws IOException { return in.read(); } public int read(byte b[], int off, int len) throws IOException { return in.read(b, off, len); } public long skip(long n) throws IOException { return in.skip(n); }} SAP 2007 / Page 32Extending java.io New ClassLowerCaseInputStream.javapublic class LowerCaseInputStream extends FilterInputStream { public LowerCaseInputStream(InputStream in) { super(in); } public int read() throws IOException { int c = super.read(); return (c == -1 ? c : Character.toLowerCase((char)c)); } public int read(byte[] b, int offset, int len) throws IOException { int result = super.read(b, offset, len); for (int i = offset; i < offset+result; i++) { b[i] = (byte)Character.toLowerCase((char)b[i]); } return result; }} SAP 2007 / Page 33LowerCaseInputStream.java Test Drivepublic class InputTest { public static void main(String[] args) throws IOException { int c; try { InputStream in = new LowerCaseInputStream( new BufferedInputStream( new FileInputStream("test.txt")));

while((c = in.read()) >= 0) { System.out.print((char)c); }

in.close(); } catch (IOException e) { e.printStackTrace(); } }} SAP 2007 / Page 34Set up the FileInputStream and decorate it, first with a BufferedInputStream and then with our brand new LowerCaseInputStream filterRemember!Inheritance is one form of extension, but there are other ways to do the sameDesigns should allow behavior to be extended without the need to modify existing codeDecorator Pattern involves a set of decorator classes that are used to wrap concrete classesYou can wrap a component with any number of decoratorsWe use inheritance to achieve the type matching, but we arent using inheritance to get behaviorDecorators can result in many small objects in our design, and overuse can be complex SAP 2007 / Page 35Decorator and AdapterDecoratorAdapterBoth wrap concrete implementations of some typeDecorator wraps to add functionality/responsibilityAdapter alters the interface it converts one interface to another SAP 2007 / Page 36Faade PatternFacade defines a higher-level interface that makes the sub-system easier to useDo not create design that have a large number of classes coupled together so that changes in one part of the system cascade to other partsWhen you build a lot of dependencies between many classes, you are building a fragile system that will be costly to maintain and complex for others to understandPatterns Team understands Faade better than many people Threading in Java is also another example of Faade Pattern

SAP 2007 / Page 37Class Diagram for Faade Pattern SAP 2007 / Page 38

SAP 2007 / Page 39Command PatternObserver PatternBehavioral Patterns

#Command PatternEncapsulate a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undo operations.A command class is a convenient place to collect code and data related to a command. A command object can hold information about the command, such as its name or which user launched it; and answer questions about it, such as how long it will likely take. The command is a useful abstraction for building generic componentsThe Command Pattern decouples an object, making a request from the one that knows how to perform itSmart Command objects implement the request themselves rather than delegating it to a receiver SAP 2007 / Page 40Home Automation through Command PatternLight.javapublic class Light { public Light() { }

public void on() { System.out.println("Light is on"); } public void off() { System.out.println("Light is off"); }}

SAP 2007 / Page 41Command.javapublic interface Command {public void execute();public void undo();} SAP 2007 / Page 42LightOnCommand.javapublic class LightOnCommand implements Command {Light light; public LightOnCommand(Light light) {this.light = light;} public void execute() {light.on();} public void undo() {light.off();}} SAP 2007 / Page 43LightOffCommand.javapublic class LightOffCommand implements Command {Light light; public LightOffCommand(Light light) {this.light = light;} public void execute() {light.off();} public void undo() {light.on();}} SAP 2007 / Page 44Test Drive Command Pattern RemoteLoader.javapublic class RemoteLoader { public static void main(String[] args) {RemoteControlWithUndo remoteControl = new RemoteControlWithUndo(); Light livingRoomLight = new Light("Living Room"); LightOnCommand livingRoomLightOn = new LightOnCommand(livingRoomLight);LightOffCommand livingRoomLightOff = new LightOffCommand(livingRoomLight); livingRoomLightOn.execute() ; livingRoomLightOff.execute();}} SAP 2007 / Page 45Test Drive Faade and Command Pattern TogetherYou need to look at the code now. SAP 2007 / Page 46Class Diagram for Command Pattern SAP 2007 / Page 47

Observer PatternDefine a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.

SAP 2007 / Page 48

Subject Interface Isubject.javapublic interface ISubject {public void registerObserver( IObserver o ) ;public void removeObserver( IObserver o ) ;public void notifyObservers() ;} SAP 2007 / Page 49Observer Interface IObserver.javapublic interface IObserver {public void notify( int temp , int humidity , int pressure ) ;} SAP 2007 / Page 50Design Principle SAP 2007 / Page 51The Subject doesnt care, it will deliver notifications to any object that implements the Observer Interface

Loosely coupled designs allow us to build flexible OO Systems that can handle change because they minimize the interdependency between objects

Pull is considered more Correct than Push

Swing makes heavy use of the Observer Pattern

Observer Pattern defines a one-to-many relationship between objects SAP 2007 / Page 52Thank you!

#ReferencesHead First Design PatternsEric & Elizabeth Freeman with Kathy Sierra & Bert BatesWikipediahttp://en.wikipedia.org/wiki/Design_pattern_%28computer_science%29YouTubehttp://www.youtube.com/codingkriggs SAP 2007 / Page 53 SAP 2007 / Page 54Secondary color palette100%Primary color palette 100%Definition and halftone values of colorsRGB 68/105/125RGB 96/127/143RGB 125/150/164RGB 152/173/183RGB 180/195/203RGB 4/53/123RGB 240/171/0RGB 102/102/102RGB 153/153/153RGB 204/204/204RGB 21/101/112RGB 98/146/147RGB 127/166/167RGB 154/185/185RGB 181/204/204RGB 85/118/48RGB 110/138/79RGB 136/160/111RGB 162/180/141RGB 187/200/172RGB 119/74/57RGB 140/101/87RGB 161/129/118RGB 181/156/147RGB 201/183/176RGB 100/68/89RGB 123/96/114RGB 147/125/139RGB 170/152/164RGB 193/180/189RGB 73/108/96RGB 101/129/120RGB 129/152/144RGB 156/174/168RGB 183/196/191RGB 129/110/44RGB 148/132/75RGB 167/154/108RGB 186/176/139RGB 205/197/171RGB 132/76/84RGB 150/103/110RGB 169/130/136RGB 188/157/162RGB 206/183/18785%70%55%40%RGB 158/48/57Tertiary color palette100%85%70%55%40%SAP BlueSAP GoldSAP Dark GraySAP GraySAP Light GrayDovePetrolViolet/MauveWarm RedWarm GreenCool GreenOcherWarning RedCool Red #