Grouping Design Patterns | My Assignment Tutor

12/04/20191Creational structuraland behaviouraldesign patternsWeek 8 & 9What is Design Pattern• Addresses a recurring design problem that arises inspecific design situations and presents a solution to it.• Constitutes a set of rules describing how to accomplishcertain tasks in software development• Focus more on reuse of recurring architectural designthemes, while frameworks focus on detailed design andimplementation• Identify and specify abstractions that are above the level ofsingle classes and instances or of components. (Gamma,Johnson, and Vlissides, 1993)• Helps in improving code quality12/04/20192Grouping Design Patterns• Creational patterns create objects for you rather thanhaving you instantiate objects directly. Gives program moreflexibility in deciding which objects need to be created fora given case• Structural patterns help you compose groups of objectsinto larger structures, such as complex user interfaces oraccounting data.• Behavioral patterns help you define the communicationbetween objects in your system and how the flow iscontrolled in a complex program.Patterns solve software structural problemslike:• Abstraction,• Encapsulation• Information hiding• Separation of concerns• Coupling and cohesion• Separation of interface and implementation• Single point of reference• Divide and conquer12/04/20193Patterns also solve non-functional problemslike:• Changeability• Interoperability• Efficiency• Reliability• Testability• ReusabilityGrouping Design Patterns – Examples CreationalStructuralBehavioralAbstract FactoryAdapterIteratorFactory MethodFaçadeObserverBuilderProxyMediatorSingletonCompositeCommandPrototypeBridgeTemplateMethod 12/04/20194Types of PatternThere are 3 types of pattern …– Creational: address problems of creating anobject in a flexible way. Separate creation, fromoperation/use.– Structural: address problems of using O-Oconstructs like inheritance to organize classesand objects– Behavioral: address problems of assigningresponsibilities to classes. Suggest both staticrelationships and patterns of communication(use cases)Patterns, Architectures &Frameworks• There can be confusion between patterns,architectures and frameworks.• Let’s try to distinguish them:• Architectures model software structure atthe highest possible level, and give theoverall system view. An architecture can usemany different patterns in differentcomponents12/04/20195• Patterns are more like small-scale or localarchitectures for architectural componentsor sub-components• Frameworks are partially completedsoftware systems that may be targeted at aparticular type of application. These aretailored by completing the unfinishedcomponents.Summary of Differences• Patterns are more general and abstract thanframeworks. A pattern is a description of asolution, not a solution itself.• A pattern cannot be directly implemented.An implementation is an example of apattern.• Patterns are more primitive thanframeworks. A framework can employseveral patterns.12/04/20196Catalogues & Languages• Patterns are grouped into catalogues andlanguages• A catalogue is group of patterns that maybe reasonable to use together• A language is a more closely relatedcollection useful for a common problemdomain, e.g. Banking.Pattern Templates• Different authors use different templates todescribe their patterns• Information is not always presented in thesame way.• Consult your manual/source !!!• A typical template would be …12/04/20197• Name: meaningful text that reflects the problem,e.g. Bridge, Mediator, Flyweight• Problem addressed: intent of the pattern,objectives achieved within certain constraints• Context: circumstances under which it can occur,used to determine applicability• Forces: constraints or issues that solution mustaddress, forces may conflict!• Solution: the static and dynamic relationshipsamong the pattern components. Structure,participants, collaboration. Solution must resolveall forces!Pattern: Singleton (Creational)Name: SingletonProblem:How can we guarantee that one and only oneinstance of a class can be created?Context: In some applications it is importantto have exactly one instance of a class, e.g. sales ofone company.12/04/20198Forces: Can make an object globally accessible as aglobal variable, but this violates encapsulation.Could use class (static) operations and attributes, butpolymorphic redefinition is not always possible.Solution:Create a class with a class operation getInstance().When class is first accessed, this creates relevantobject instance and returns object identity to client.On subsequent calls of getInstance(), no newinstance is created, but identity of existing object isreturned.Singleton Structure Singleton-uniqueInstance-singletonData+getInstance( )+getSingletonData( )+singletonOperation( )-Singleton( ) Object identifier for singletoninstance, class scope or staticReturns object identifier forunique instance, class-scopeor staticPrivate constructor only accessiblevia getInstance()getInstance( ) {if ( uniqueInstance == null ){ uniqueInstance = new Singleton( ) }return uniqueInstance}12/04/20199Class Singleton {private static Singleton uniqueInstance = null;private Singleton( ) { .. } // private constructorpublic static Singleton getInstance( ) {if (uniqueInstance == null)uniqueInstance = new Singleton();// call constructorreturn uniqueInstance;}}Example: CodeComments• To specify a class has only one instance, we makeit inherit from Singleton.+ controlled access to single object instance throughSingleton encapsulation+ Can tailor for any finite number of instances+ namespace not extended by global variables– access requires additional message passing– Pattern limits flexibility, significant redesign ifsingleton class later gets many instances12/04/201910Pattern: Façade (Structural)Name: FaçadeProblem:How can we access a large number of classeswith a complex internal interaction in a simplebut safe way?Solution: Introduce a dedicated interface classthat simplifies the view of the class collection.Facade StructureFacadesubsystem classes12/04/201911 SecurityManager+addAccessRight()+addActor()+addActorRole()+removeActor() AccessRight+addAccessRight() Actor+addActor()+removeActor()+changeSalary() ActorRole+addActorRole() Method not in FacadePattern NameComments• Clients communicate with the subsystem bysending requests to Façade which forwardsthem to the appropriate subsystem object(s).• Although subsystem objects perform actualwork, Façade may have to translate itsinterface to subsystem interfaces.• Clients that use the Façade don’t have toaccess its subsystem objects directly.12/04/201912• Usually only one Façade object isrequired. Thus a Façade object is often asingleton.• Factory pattern can be used with Façadeto provide an interface for creatingsubsystem objects in a subsystemindependent way.• Factory can also be used as an alternativeto Façade to hide platform-specific classes.• Mediator pattern is similar to Façade inabstracting functionality of classes.Pattern: Mediator (Behavioral)Problem:How can we deal with two or more classeswhich sometimes interact, but can also be usedseparately?Solution: Mediator promotes loose couplingby keeping objects from referring to one anotherexplicitly. Put each interaction between objectsin a separate (Mediator) class. This classshould have references to the objects.12/04/201913• A pattern for two objects which existindependently but have some coupling. Thiscoupling is placed in its own class.• Used by e.g. ActionListener in graphicswhich couples together two graphicalobjects, e.g. window & buttonMediator Structure MediatorColleague ConcreteMediator*ConcreteConcrete* 1 mediatorColleague1Colleague212/04/201914• Colleagues send and receive requests from aMediator object. The mediator implementsthe cooperative behavior by routing requestsbetween appropriate colleagues.Example: Top-Down Design MediatorColleague File_SelectorBrowserText_FieldButton*** 1 mediatorMy_Application 12/04/201915Comments• Façade, unlike Mediator, abstracts asubsystem of objects to provide aconvenient interface. Unidirectional.Façade objects make requests of thesubsystem, but not vice-versa.• Mediator enables cooperative behaviour,that colleagues don’t or can’t provide.Multidirectional.• Observer pattern and Mediator bothreceive notification of changes.• Observer does so through an abstractmechanism. Allows source of notification tobe independent of its observers.• In Mediator, the source must know itsmediator. This makes it possible formediator to define reactions to eachstimulus.12/04/201916Pattern: Observer (Behavioral)Name: ObserverProblem: Define a one-to-many dependencyamong objects so that when one objectchanges state, all of its dependents arenotified and updated automatically.Solution: MVC, but refined by separatingabstract from concrete subjects and observers Observerfor all o inobservers {Update() ConcreteObserverobserverStateupdate()*returnsubjectState SubjectConcreteSubjectattach(Observer)detach(Observer)notify()subjectState()getState()setState()*observerState =subject.getState( )o.update( ) }12/04/201917• ConcreteSubject notifies its observerswhenever a change occurs that could makeits observers state inconsistent with its own• After being informed of change, aConcreteObserver queries the subject toreconcile its state with subjects.• Observer object that initiates changerequest postpones its update until it getsnotification from subject. Notify() is notalways called by subject. Can be called byan observer, or any other object.• Pattern is well known, has wide range ofvariantsaConcreteSubject:aConcreteSubject:aConcreteSubject: setState( )notify( )update( )getState( )update( )getState( ) 12/04/201918Pattern: Mock Object• A pattern where coupling an objectscoupling to another complex object isreplaced by coupling to a simplified proxy.• C.f. dummy methods in whishful thinking• Coupling between objects could well be aninterface. Then the mock and real objectsimplement this interface.• Used e.g. in testing objects. (see Section 8)Pattern: FactoryName: (Abstract) FactoryProblem: Provide an interface for creatingfamilies of related or dependent objectswithout specifying their concrete classes.• Control instantiation• Singleton is a special case of Factory whereonly one object can be created.12/04/201919Factory StructureAbstractProduct ConcreteProduct1 AbstractFactoryFactoryMethod()AnOperation() ConcreteFactoryFactoryMethod() Product =FactoryMethod()return newConcreteProduct()• Normally, a single instance of aConcreteFactory class is created atruntime.• This creates product objects having aparticular implementation.• To create different product objects, clientsshould use a different concrete factory.• AbstractFactory defers creation of productobjects to its ConcreteFactory subclasses.12/04/201920 MyClasscreateObjectOfRequiredClass():RequiredClassFactory design patternClientRequiredClasscreate objects Factory Class ModelFactory Example• E.g. create objects of different types• We can order a Car and get anAston Martin, MG, Jaguar etc• We don’t know which factory builds the car,just that they implement CarFactory.Owner has created the actual factoryinstance.12/04/201921// we have a reference to ownerCarFactory aFactory = owner.makefactory();Car myCar =aFactory.makeCar(“AstonMartin”);class BritishFactory implements CarFactory{public Car makeCar(String b) throwsException {if(b.equals(“AstonMartin”)) return newAstonMartin();else if (..) return ..;else throw new Exception(b + “doesn’texist”);}}Class AstonMartin extends Car {}Class Jaguar extends Car {}Interface CarFactory {Public Car makeCar(String b) throws Exception;}12/04/201922• Abstract Factory classes are oftenimplemented with the Factory Methodpattern.• Can also be implemented using thePrototype pattern.• A concrete factory is often a Singleton.CommentsCommandName: CommandProblem: Need a flexible organization formethods that allows them to be contextsensitive in a structured way.Solution: Place behaviour /operation in anown class instead of in a method.12/04/201923Examples• Undo. It’s difficult to undo effects of anarbitrary method. Methods vary over time.• Choose menu option. Whether an optioncan be chosen at any time depends on manyfactors.Command Structure CommandExecute() ConcreteCommandExecute()State Receiver.Action()Client Invoker1ReceiverAction()1receiver12/04/201924• Client creates a ConcreteCommand objectand specifies its receiver.• An Invoker object stores theConcreteCommand object• The invoker issues a request by callingExecute on the command. When commandsare undoable, ConcreteCommand storesstate for undoing the command beforeinvoking Execute• ConcreteCommand object invokesoperations on its receiver to carry out requestaClient aCommand anInvoker aReceivernew Command(aReceiver) Execute()storeCommand(aCommand)Action() 12/04/201925Comments• Pattern replaces function pointers (passingfunctions as parameters) which is notavailable in some languages.• Pattern allows a class to call a receiversroutine without knowledge of it. Gives highdegree of decoupling between caller andcallee.Command (Cont.)• Client:Command command =Command.getCommand (…);• Command.execute();• A Factory method first gives a Commandobject (means object can depend on currentsituation)• Then call execution command execute()12/04/201926class Command {public void execute() {if (check-something) { //menu itemselectable?this.getParameters(); //preparationgetTarget1().action1(); //do something}else// do something else,// like other action or target}}Related Patterns• A Memento pattern can be used the keepthe state a command needs to undo itseffect.• A command that must be copied beforebeing placed on the history list acts as aPrototype pattern.12/04/201927Guidelines Checklist• Is there a pattern that addresses my problem?• Does the pattern provide an acceptable solution?• Is there a simpler solution? (pattern overuse)• Is the context of the pattern consistent with myproblem?• Are the consequences of using the patternacceptable?• Are there forces in my environment that conflictwith the use of the pattern?Benefits and Dangers+ support software reuse+ language for discussing high-level problems+ access to experience and knowledge– limit creativity?– needs a culture of reuse– needs organisational education


Leave a Reply

Your email address will not be published. Required fields are marked *