Presentation is loading. Please wait.

Presentation is loading. Please wait.

Design Patterns (Part 1) Design Patterns are time-tested solutions to recurring design problems. Are the answer to a question that commonly arises “How.

Similar presentations

Presentation on theme: "Design Patterns (Part 1) Design Patterns are time-tested solutions to recurring design problems. Are the answer to a question that commonly arises “How."— Presentation transcript:

1 Design Patterns (Part 1) Design Patterns are time-tested solutions to recurring design problems. Are the answer to a question that commonly arises “How can I … ?”

2 Why Study Patterns? Can reuse solutions –Gives us a head start (mostly design, but implementation too) –Avoids unanticipated results as we are using time-tested solutions –No need to reinvent the wheel Establish common terminology –Design patterns provide a common point of reference

3 Is This A New Idea? Town planners and architects talk of design patterns all the time. Design patterns have their roots in the work of Christopher Alexander an architect. When talking about patterns in buildings and towns in 1977, he wrote “Each pattern describes a problem which occurs over and over again in our environment and then describes the core of the solution to the problem, in such a way that you can use this solution a million times over, without doing it the same way twice.” Christopher Alexander,

4 Shortly after, software professionals began to incorporate Alexander’s principle into the creation of early design pattern documentation as a guide to novice developers. Design patterns gained popularity in computer science after a certain book was published in 1994 by four authors, commonly know as Gang of Four or GOF

5 Gang of Four The GoF Book Gang of Four (GoF) Gamma, Helm, Johnson, Vlissides, - founders of movement. Gamma et al, Design Patterns: Elements of Reusable Object-Oriented Software, Addison Wesley, They offer advice and help for developing quality software An object-oriented design pattern systematically names, explains and evaluates an important and recurring design in object-oriented systems

6 Patterns solve software structural problems like: Abstraction, Encapsulation Information hiding Separation of concerns Coupling and cohesion Separation of interface and implementation Single point of reference Divide and conquer

7 Patterns also solve non-functional problems like: Changeability Interoperability Efficiency Reliability Testability Reusability

8 Design Patterns Template TermDescription Pattern NameDescribes the essence of the pattern in a short, but expressive, name IntentDescribes what the pattern does Also Known AsList any synonyms for the pattern MotivationProvides an example of a problem and how the pattern solves that problem ApplicabilityLists the situations where the pattern is applicable StructureSet of diagrams of the classes and objects that depict the pattern ParticipantsDescribes the classes and objects that participate in the design pattern and their responsibilities CollaborationsDescribes how the participants collaborate to carry out their responsibilitiescollaborate ConsequencesDescribes the forces that exist with the pattern and the benefits, trade- offs, and the variable that is isolated by the pattern

9 Different authors use different templates to describe their patterns Information is not always presented in the same way. Namemeaningful text that reflects the problem, e.g. Bridge, Mediator, Flyweight Problem addressedintent of the pattern, objectives achieved within certain constraints Contextcircumstances under which it can occur Forcesconstraints or issues that solution must address, forces may conflict! Solutionthe static and dynamic relationships among the pattern components. Structure, participants, collaboration. Solution must resolve all forces! Consult your manual/source !!!

10 Types of Pattern There are 3 types of pattern … –Creational: address problems of creating an object in a flexible way. Separate creation, from operation/use. –Structural: address problems of using O-O constructs like inheritance to organize classes and objects –Behavioral: describe the ways objects and classes interact and divide responsibilities among themselves.

11 Creational Patterns Abstract Factory –Creates families of related or dependent objects Builder –Separates an object’s construction from its representation Factory Method –Creates instances of several derived classes Prototype –A fully initialized instance to be copied or cloned Singleton –A class of which only a single instance can exist

12 Structural Patterns Adapter –Match interfaces of different classes Bridge –Separates an object’s interface from its implementation Composite –A tree structure of simple and composite objects Decorator –Add responsibilities to objects dynamically Façade –A single class that represents an entire subsystem Flyweight –A fine-grained instance used for efficient sharing Proxy –An object representing another object

13 Behavioral Patterns Chain of Responsibility –A way of passing a request between a chain of objects Command –Encapsulate a command request as an object Interpreter –A way to include language elements in a program Iterator –Sequentially access the elements of a collection Mediator –Define simplified communication between classes Memento –Capture and restore an object's internal state Observer –A way of notifying change to a number of classes State –Alter an object's behavior when its state changes Strategy –Encapsulate an algorithm inside a class Template Method –Defer the exact steps of an algorithm to a subclass Visitor –Define a new operation for a class without changing the class

14 Pattern: Singleton (Creational) Name: Singleton Problem: How can we guarantee that one and only one instance of a class can be created? Context: In some applications it is important to have exactly one instance of a class, e.g. sales of one company, or one shopping basket on website.

15 Forces: Can make an object globally accessible as a global variable, but this violates encapsulation. Could use class (static) operations and attributes, but polymorphic redefinition is not always possible. Solution: Create a class with a class operation getInstance(). When class is first accessed, this creates relevant object instance and returns object identity to client. On subsequent calls of getInstance(), no new instance is created, but identity of existing object is returned.

16 Singleton Structure Singleton -uniqueInstance -singletonData +getInstance( ) +getSingletonData( ) +singletonOperation( ) -Singleton( ) Object identifier for singleton instance, class scope or static Returns object identifier for unique instance, class-scope or static Private constructor only accessible via getInstance() getInstance( ) { if ( uniqueInstance == null ) { uniqueInstance = new Singleton( ) } return uniqueInstance }

17 Class Singleton { private static Singleton uniqueInstance = null; private Singleton( ) {.. } // private constructor public static Singleton getInstance( ) { if (uniqueInstance == null) uniqueInstance = new Singleton(); // call constructor return uniqueInstance; } Example: Code

18 Real-World Design Pattern Usage The designers of the Microsoft.Net Framework were well aware of many different patterns. Microsoft has a team dedicated to incorporating design patterns into the framework. The Microsoft patterns & practices team works with design patterns and higher-level combinations of patterns

19 Comments To specify a class has only one instance, we make it inherit from Singleton. + controlled access to single object instance through Singleton 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 if singleton class later gets many instances

20 Singleton Pattern Versus Static Class Static class example [C#] // Static class example. Note the static keyword usage. static public class SiteStatic { // The data must be a static member in this example. static object[] _data = new object[10]; // C# doesn't define when this constructor is run, but it will likely // be run right before it is used. static SiteStatic() { // Initialize all of our static members. } }

21 Singleton advantages Singletons preserve the conventional class approach, and don't require that you use the static keyword everywhere. They may be more demanding to implement at first, but will greatly simplify the architecture of your program. Unlike static classes, we can use singletons as parameters or objects. Using singleton as parameter [C#] // We want to call a function with this structure as an object. // Get a reference from the Instance property on the singleton. SiteStructure site = SiteStructure.Instance; OtherFunction(site); // Use singleton as parameter.

22 Interface example You can use singletons with interfaces just like any other class. In the C# language, an interface is a contract, and objects that have an interface must meet all of the requirements of that interface. Singletons used with interface [C#] /// Stores signatures of various important methods related to the site. public interface ISiteInterface { }; /// Skeleton of the singleton that inherits the interface. class SiteStructure : ISiteInterface { // Implements all ISiteInterface methods. // [omitted] } /// Here is an example class where we use a singleton with the interface. class TestClass { public TestClass() { // Send singleton object to any function that can take its interface. SiteStructure site = SiteStructure.Instance; CustomMethod((ISiteInterface)site); } /// Receives a singleton that adheres to the ISiteInterface interface. private void CustomMethod(ISiteInterface interfaceObject) { // Use the singleton by its interface. } }

23 Singletons allow you to reuse code and control object state much easier. This improves code-sharing, and can result in a far cleaner body of code. With less code, your programs will usually have fewer bugs and will be easier to maintain. Summary

24 Pattern: Observer (Behavioral) Name: Observer Problem: Define a one-to-many dependency among objects so that when one object changes state, all of its dependents are notified and updated automatically. Solution: MVC, but refined by separating abstract from concrete subjects and observers

25 Observer ConcreteObserver notify() observerState notify() Subject ConcreteSubject Register(Observer) Unregister(Observer) notifyobservers() subjectState() getState() setState() * * observerState = subject.getState( ) return subjectState for all o in observers { o.notify( ) }

26 ConcreteSubject notifies its observers whenever a change occurs that could make its observers state inconsistent with its own After being informed of change, a ConcreteObserver queries the subject to reconcile its state with subjects. Observer object that initiates change request postpones its update until it gets notification from subject. Notify() is not always called by subject. Can be called by an observer, or any other object. Pattern is well known, has wide range of variants

27 Push vs Pull Push means that the observable will always push the data to observers, whether they need it or not. Pull : Observers have the liberty of reaching for the data which makes sense for them [I mean, they might be observing a particular field, but only need to be notified if the field crosses some threshold], and hence can reduce on network traffic, and your application performance.

Download ppt "Design Patterns (Part 1) Design Patterns are time-tested solutions to recurring design problems. Are the answer to a question that commonly arises “How."

Similar presentations

Ads by Google