Friday, January 26, 2018

Design Patterns


A pattern is a general reusable solution to a commonly occurring problem.
Design patterns deal specifically with problems at the level of software design.
At the coding level: programming idioms
At the architecture level: architectural patterns


Design Patterns: Elements of Reusable Object-Oriented Software is a software engineering
book describing software design patterns. The book's authors are Erich Gamma, Richard Helm,
Ralph Johnson and John Vlissides with a foreword by Grady Booch. The book is divided into
two parts, with the first two chapters exploring the capabilities and pitfalls of object-oriented
programming, and the remaining chapters describing 23 classic software design patterns.
The book includes examples in C++ and Smalltalk.
It has been influential to the field of software engineering and is regarded as an important source
for object-oriented design theory and practice. More than 500,000 copies have been sold in
English and in 13 other languages. The authors are often referred to as the Gang of Four (GoF).




Architectural Patterns are related to large-scale design; typically applied during early iterations
(the elaboration phase)


Programming Idioms are specific to a particular programming language such as C++ and use
features of the language features.
Design Patterns are related to Larman’s GRASP principles which can be seen as more basic
principles (than are used in design patterns)
Design Patterns document design experience – explicitly capture knowledge that experienced
developers already understand implicitly.
Enable widespread reuse of software architecture.
Help to transcend programming language-centric viewpoints.


Programming Idioms
Means of expressing a recurring construct in one or more programming languages:
Simple idioms include:
swapping values between variables
incrementing a counter
traversing a list
read ahead
Screenshot_2017-02-04_16-57-26.png

Expressing a Design Pattern


The following are typical constituents of a design pattern (some may not always be expressed):
Name : meaningful name to allow identification
Problem : statement of problem, describes the goals and objectives
Context : preconditions under which problem occurs.
Forces : constraints and how they interact or conflict with one another; tradeoffs
Solutions : how to realize the desired outcome; describe static structure and dynamic behaviour
Examples : sample implementation
Result state : state of system after pattern has been applied
Rationale : explanation of rules in the pattern
Related Patterns    : relationships between this pattern and others
Known Uses : Known occurrences of a pattern


GoF Patterns (Patterns described in the above book)


There are 23 GoF Patterns, classified under:
Creational Design Patterns deal with object creation mechanisms, trying to create objects
in a manner suitable to the situation.
Structural Design Patterns identify simple ways to realize relationships between entities.
Behavioral Design Patterns identify common communication patterns between objects and
realize these patterns.


Our Syllabus
We will focus on 6 common design patterns
  1. Adapter
  2. Singleton
  3. Strategy
  4. Factory
  5. Observer
  6. Visitor


Adapter Pattern


  • Context/Problem: How to resolve incompatible interfaces or provide stable
interface to similar components with different interfaces
  • Solution: Convert the original interface of component into another interface
through intermediate adaptor object
  • Also known as Wrapper
  • The client and the adapted object remain independent


Motivation
  • Sometimes a toolkit class that’s designed for reuse isn’t reusable only because its
interface doesn’t match the domain-specific interface an application requires.
  • Consider for example a drawing editor that lets users draw and arrange graphical
elements (lines, polygons, text, etc.) into pictures and diagrams.
  • The drawing editor’s key abstraction is the graphical object, which has an editable
shape and can draw itself.
  • The interface for graphical objects is defined by an abstract class called Shape.
  • The editor defines a subclass of Shape for each kind of graphical object: a LineShape
class for lines, a PolygonShape class for polygons, and so forth.
  • Classes for elementary geometric shapes like LineShape and PolygonShape are rather
easy to implement, because their drawing and editing capabilities are inherently limited. But a
TextShape subclass that can display and edit text is considerably more difficult to implement,
since even basic text editing involves complicated screen update and buffer management.
  • Meanwhile, an off-the-shelf user interface toolkit might already provide a sophisticated
TextView class for displaying and editing text.
  • Ideally we’d like to reuse TextView to implement TextShape, but the toolkit wasn’t
designed with Shape classes in mind. So we can’t use TextView and Shape objects interchangeably.


Solution
Instead, we could define TextShape so that it adapts the TextView interface to Shape’s.


We can do this in one of two ways:
  1. by inheriting Shape’s interface and TextView’s implementation or
  2. by composing a TextView instance within a TextShape and implementing TextShape in
terms of TextView’s interface.
These two approaches correspond to the class and object versions of the Adapter pattern.
We call TextShape an adapter.


Screenshot_2017-02-05_01-42-36.png

Trade Offs : Class and object adapters have different trade-offs.
Class Adapter
Object Adapter
Adapter overrides some of adapter’s behaviour
because Adaptor is a subclass of Adaptee.

Not for adopt a class and all its subclasses

Adapts adaptee to target by committing to a
concrete adapter class

Introduces only one object.
Make hard to override Adaptee's behaviour


A single adapter work with many adoptees
(adoptee and its subclasses)
Can add functionality to all adaptees at once.

Subclass Adaptee makes Adapter refer to it.


Below is a quick sketch of the implementation for the Shape example given above, using
the class adaptor.
BoundingBox requests, declared in class Shape, are converted to GetExtent requests
defined in TextView. Since TextShape adapts TextView to the Shape interface, the drawing
editor can reuse the otherwise incompatible TextView class.


Screenshot_2017-02-05_01-50-25.png




Adapter pattern works as a bridge between two incompatible interfaces. This type of design pattern
comes under structural pattern as this pattern combines the capability of two independent interfaces.
This pattern involves a single class which is responsible to join functionalities of independent or
incompatible interfaces. A real life example could be a case of card reader which acts as an adapter
between memory card and a laptop. You plugin the memory card into card reader and card reader
into the laptop so that memory card can be read via laptop.
We are demonstrating use of Adapter pattern via following example in which an audio player device
can play mp3 files only and wants to use an advanced audio player capable of playing vlc and mp4 files.


Singleton Pattern
Context/Problem: Exactly one instance of class is allowed – it is a “singleton.” Objects
need a global, single point of access
Solution: Define a static method of the class that returns the singleton
Global visibility is needed through a single access point
Use of public constructor cannot guarantee that no more than one instance will be created
  • Have private class variable, possibly called theInstance that stores instance
  • Have public class method (static method) possibly called getInstance
  • First time method is called, it creates single instance and stores it in theInstance.
  • Subsequent calls simply return theInstance
  • If class has constructor it should be private; ensures no other class will be able to
create it directly


Motivation
It’s important for some classes to have exactly one instance. Although there can be many
printers in a system, there should be only one printer spooler. There should be only one file
system and one window manager. A digital filter will have one A/D converter. An accounting
system will be dedicated to serving one company
Screenshot_2017-02-05_01-59-49.png
Singleton
Defines an Instance operation that lets clients access its unique instance. getInstance()
is a class operation.
Clients access the singleton solely through the singleton’s getInstance() operation.

Implementation
Screenshot_2017-02-05_02-03-17.png


This type of design pattern comes under creational pattern as this pattern provides one of the
best ways to create an object.
This pattern involves a single class which is responsible to create an object while making sure
that only single object gets created. This class provides a way to access its only object which
can be accessed directly without need to instantiate the object of the class.

Strategy Pattern


Context/Problem: How to design for varying but related algorithms or policies?
How to design for the ability to change these algorithms and policies?
Solution: Define each algorithm/policy/strategy in a separate class, with a
common interface
Example: Different pricing strategies.
Solution: Introduce common interface. Each getTotal method has different algorithm.



In Strategy pattern, a class behavior or its algorithm can be changed at run time. This type of
design pattern comes under behavior pattern.
In Strategy pattern, we create objects which represent various strategies and a context object
whose behavior varies as per its strategy object. The strategy object changes the executing
algorithm of the context object.
We are going to create a Strategy interface defining an action and concrete strategy classes
implementing the Strategy interface. Context is a class which uses a Strategy.
StrategyPatternDemo, our demo class, will use Context and strategy objects to demonstrate
change in Context behaviour based on strategy it deploys or uses.




Factory Pattern


Factory pattern is one of the most used design patterns in Java. This type of design pattern
comes under creational pattern as this pattern provides one of the best ways to create an object.
In Factory pattern, we create object without exposing the creation logic to the client and refer
to newly created object using a common interface.
We're going to create a Shape interface and concrete classes implementing the Shape
interface. A factory class ShapeFactory is defined as a next step.
FactoryPatternDemo, our demo class will use ShapeFactory to get a Shape object.
It will pass information (CIRCLE / RECTANGLE / SQUARE) to ShapeFactory to get
the type of object it needs.


Abstract Factory Pattern


Abstract Factory patterns work around a super-factory which creates other factories.
This factory is also called as factory of factories. This type of design pattern comes
under creational pattern as this pattern provides one of the best ways to create an object.
In Abstract Factory pattern an interface is responsible for creating a factory of related
objects without explicitly specifying their classes. Each generated factory can give the
objects as per the Factory pattern.
We are going to create a Shape and Color interfaces and concrete classes implementing
these interfaces. We create an abstract factory class AbstractFactory as next step.
Factory classes ShapeFactory and ColorFactory are defined where each factory extends
AbstractFactory. A factory creator/generator class FactoryProducer is created.
AbstractFactoryPatternDemo, our demo class uses FactoryProducer to get a
AbstractFactory object. It will pass information (CIRCLE / RECTANGLE /
SQUARE for Shape) to AbstractFactory to get the type of object it needs.
It also passes information (RED / GREEN / BLUE for Color) to AbstractFactory
to get the type of object it needs.

Observer Pattern


Context/Problem: Different kinds of subscriber objects are interested in the state
changes or events of publisher object, and want to react in their own unique way
when the publisher generates event Publisher wants to maintain low coupling to
subscribers


Solution: Define a subscriber interface Subscribers implement this interface
Publisher can dynamically register subscribers who are interested in an event
and notify them when the event occurs


Also know as Publish-Subscribe or Delegation Event Model (in Java)




Observer pattern is used when there is one-to-many relationship between objects such as if
one object is modified, its depenedent objects are to be notified automatically.
Observer pattern falls under behavioral pattern category.


Observer pattern uses three actor classes. Subject, Observer and Client.
Subject is an object having methods to attach and detach observers to a client object.
We have created an abstract class Observer and a concrete class Subject that is extending
class Observer.
ObserverPatternDemo, our demo class, will use Subject and concrete class object to
show observer pattern in action.


Visitor Pattern




In Visitor pattern, we use a visitor class which changes the executing algorithm of an
element class. By this way, execution algorithm of element can vary as and when visitor
varies. This pattern comes under behavior pattern category. As per the pattern, element
object has to accept the visitor object so that visitor object handles the operation on the
element object.
We are going to create a ComputerPart interface defining accept opearation.Keyboard,
Mouse, Monitor and Computer are concrete classes implementing ComputerPart interface.
We will define another interface ComputerPartVisitor which will define a visitor class
operations. Computer uses concrete visitor to do corresponding action.
VisitorPatternDemo, our demo class, will use Computer and ComputerPartVisitor classes
to demonstrate use of visitor pattern.



Vocabulary
Transcend - ඉක්මවා යනවා
Constituents - අඩංගු වූ, සංඝටක, කොටස
Tradeoffs - හුවමාරු කර ගැනීම
Printer Spooler - Definition of: print spooler. print spooler. Software that
manages sending jobs to the printer. When an application prints a document,
the formatted output is stored on disk, and the print spooler feeds the print
images to the printer in the background at slower printing speeds.

Questions

Part (a) is about C++ , there are 5 MCQ questions.
(b) What is the Singleton design pattern? How could it be implemented in C++?
(7 marks)
(c) What is the Adapter design pattern? Describe both the class and object adapter
methods
for implementing this pattern.
(8 marks)

No comments:

Post a Comment