Design pattern Decorator - PowerPoint PPT Presentation

1 / 42
About This Presentation
Title:

Design pattern Decorator

Description:

The singleton pattern is an improvement over global variables. ... The pattern makes it easy to change your mind and allow more than one instance ... – PowerPoint PPT presentation

Number of Views:74
Avg rating:3.0/5.0
Slides: 43
Provided by: michael742
Category:

less

Transcript and Presenter's Notes

Title: Design pattern Decorator


1
Design pattern Decorator
  • aka filter, wrapper
  • Intent
  • attach additional responsibilities to an object
    dynamically.
  • use Decorator
  • to add responsibilities to individual objects
    dynamically and transparently, that is, without
    affecting other objects
  • for responsibilities that can be withdrawn
  • when extension by subclassing is impractical

2
Decorator - Structure
component
component.Operation()
super.Operation() AddedBehavior()
3
Example
  • public interface Shape
  • public Rectangle boundingBox()
  • public double area()
  • public void draw(Graphics2D g)

4
  • public class Circle implements Shape
  • private Point location
  • private double radius
  • public Circle(int x int y double rad)
  • location new Point(x,y)
  • radius rad
  • public double area()
  • return Math.pi radius radius
  • public Rectangle boundingBox()
  • int x (int) location.x radius
  • int y (int) location.y radius
  • int width (int) 2radius
  • return new Rectangle(x,y,width,width)

5
  • public class DecoratedShape implements Shape
  • private Shape shape
  • public DecoratedShape(Shape s)
  • shape s
  • public double area()
  • return shape.area()
  • public Rectangle boundingBox()
  • return shape.boundingBox()
  • public void draw(Graphics2D g)
  • shape.draw(g)

6
  • public class FramedShape extends DecoratedShape
  • public FramedShape(Shape s)
  • super(s)
  • public void draw(Graphics2D g)
  • super.draw(g)
  • g.draw(boundingBox())

7
  • public class AreaShape extends DecoratedShape
  • public AreaShape(Shape s)
  • super(s)
  • public void draw(Graphics2D g)
  • super.draw(g)
  • int x
  • int y
  • g.drawString(Area area().toString(),x,y)

8
  • Shape s new AreaShape(
  • new FramedShape (new Circle(10,10,1.0)))
  • s.draw()

Area 3.1415926
9
Adapter
  • aka Wrapper
  • a structural pattern
  • intent convert interface of a class into another
    interface clients expect
  • motivation
  • sometimes object provides appropriate behavior
    but uses a different interface than is required
  • e.g.
  • TextShape as adapted TextView in a drawing
    editor
  • Shape hierarchy
  • existing TextView class
  • modify TextView class?
  • TextShape as adapter
  • via inheritance (class adapter)
  • via composition (object adapter)

10
TextShape as Adapter
DrawingEditor
text
11
  • use
  • want to use existing class without proper
    interface
  • want to create reusable class that cooperates
    with unrelated or unforeseen classes
  • want to use several existing subclasses but
    impractical to adapt interface by subclassing
    every one
  • model
  • consequences
  • class adapter (inheritance)
  • commits to a concrete Adaptee class, cant adapt
    class and all subclasses
  • Adapter can override behavior (inheritance)
  • only one object created
  • object adapter (composition)
  • Adapter can work with multiple Adaptees (Adaptee
    class and any subclass), adding functionality to
    all Adaptees at once
  • harder to override Adaptee behavior, i.e. the
    subclasses may also override so must adapt each
    subclass as well

12
Class Adapter
Client
(implementation)
13
Object Adapter
Client
adaptee
14
Façade
  • a structural pattern
  • intent
  • provide a unified interface to a set of
    interfaces in a subsystem
  • motivation
  • most clients dont care about details
  • powerful, low-level interfaces complicate task
  • e.g. Compiler is façade for Scanner, Parser, etc.

15
Façade Motivation
client classes
Façade
subsystem classes
16
Compiler as Façade
compiler subsystem classes
Scanner
Token
Stream
Symbol
Parser
ProgramNode
ProgramNodeBuilder
ByteCodeStream
StatementNode
CodeGenerator
ExpressionNode
VariableNode
RISCCodeGenerator
StackMachineCodeGenerator
17
  • use
  • want to provide a simple interface to a complex
    subsystem
  • there are many dependencies between clients and
    implementation classes
  • model
  • Façade
  • common interface to all subsystem functions
  • delegates to appropriate subsystem object
  • subsystem classes
  • implement subsystem functionality
  • have no knowledge of Façade
  • consequences
  • shields clients from subsystem components, making
    subsystem easier to use
  • promotes weak coupling between subsystem and
    clients
  • eliminate complex dependencies
  • Java API
  • java.net URL class allows access to URLs without
    knowing the classes which support URLs

18
Singleton
  • a creational pattern
  • intent Ensure a class only has one instance, and
    provide a global point of access to it.
  • motivation
  • Some classes should have exactly one instance.
    These classes usually involve the central
    management of a resource.
  • e.g.
  • just one audio clip should be played at a time
  • an object of the class AudioClipManager is
    responsible for playing audio clips a previous
    clip is stopped before a new one is started
  • ensure that there is just one AudioClipManager

19
Example (AudioClipManager)
return instance
20
Singleton Structure Considerations
Singleton -instance Singleton -Singleton() getI
nstance() Singleton ...
return instance
  • lazy instantiation
  • create instance at load-time vs postpone creation
    until the first call of getInstance()
  • interface Clonable
  • a singleton object should not implement this
    interface
  • Object serialization
  • serialization can be used to copy objects
  • a singleton object should not implement the
    interface Serializable

21
Singleton - Consequences
  • Controlled access to sole instance. Because the
    Singleton class encapsulates its sole instance,
    it can have strict control over how and when
    clients access it.
  • Reduced name space. The singleton pattern is an
    improvement over global variables. It avoids
    polluting the name space with global variables
    that store sole instances.
  • Permits refinement of operations and
    representation. The Singleton class may be
    subclassed, and it is easy to configure an
    application with instances of this extended
    class.
  • Permits a variable number of instances. The
    pattern makes it easy to change your mind and
    allow more than one instance of the Singleton
    class (variation up to a fixed number n of
    instances). Only the operation that grants access
    to the Singleton instance needs to change.
  • More flexible than class operations. Another way
    to package a singletons functionality is to use
    class operations. This approach makes it hard to
    change a design to allow more than one instance.

22
Singleton - Example
  • The class UniversalCounter should provide a sole
    instance which
  • is capable of counting globally calls of the
    incCount() method
  • works in a multi-thread environment
  • uses lazy instantiation
  • Additional considerations
  • lazy instantiation and counting in a concurrent
    environment

23
  • public class UniversalCounter
  • private static UniversalCounter myInstance
    null
  • private int count
  • private UniversalCounter()
  • count 0
  • public static synchronized UniversalCounter
    getInstance()
  • if (myInstance null) myInstance new
    UniversalCounter()
  • return myInstance
  • public synchronized void incCount()
  • count
  • public int getCount()

24
Null object
  • a behavioral pattern
  • intent The null object pattern provides an
    alternative to using null to indicate the absence
    of an object.
  • motivation
  • using null to indicate the absence of an object
    requires a test for null before calling a method.
  • e.g.
  • we want to provide a facility which is able to
    route warnings/error messages to different
    locations
  • dialog box
  • a log file
  • nowhere at all
  • the user of this class/package should not forced
    to test for null before using it

25
Null object - Structure
Example
uses ?
Delegator
1
uses ?
Application
1
1
OperationIF
1
WarningRouter routeWarning(String)
NullOperation
RealOperation
WarningDialog
IgnoreWarning
WarningLogger
26
Null object - Example
  • public interface WarningRouter
  • public void routeWarning(String msg)
  • public class WarningDialog implements
    WarningRouter
  • public void routeWarning(String msg)
  • JOptionPane.showMessageDialog(null,
  • msg,
  • Warning,
  • JOptionPane.OK_OPTI
    ON,
  • JOptionPane.WARNING_MESSAGE)
  • public class WarningLogger implements
    WarningRouter ...
  • public class IgnoreWarning implements
    WarningRouter
  • public void routeWarning(String msg)

27
What is XML?
  • XML stands for EXtensible Markup Language
  • XML is a markup language much like HTML, but
  • all XML elements must have a closing tag
  • XML tags are case sensitive
  • All XML elements must be properly nested
  • All XML documents must have a single root element
  • Attribute values must always be quoted
  • XML was designed to describe data
  • XML tags are not predefined. You must define your
    own tags.
  • Example
  • ltnote date"12/11/2002"gt
  • lttogtRoblt/togt
  • ltfromgtJanilt/fromgt
  • ltheadinggtReminderlt/headinggt
  • ltbodygtDon't forget me this weekend!lt/bodygt
  • lt/notegt

28
Example
  • lt?xml version"1.0"?gt
  • ltfactory xSize"7" ySize"7"gt
  • ltlocationgt
  • ltfloor/gt
  • lt/locationgt
  • ltlocationgt
  • ltfloor/gt
  • ltwalls north"true" east"false"
  • south"false" west"false"/gt
  • lt/locationgt
  • ...
  • lt/factorygt

29
XML Schema
  • XML Schema is a language that can be used to
    describe the syntactical
  • structure of XML documents. It is
  • expressed in XML,
  • self-describing and simple,
  • can be used to validate XML documents,
  • W3C approved (World Wide Web Consortium).
  • An XML document may specify its schema using the
    schemaLocation
  • attribute.
  • ltfactory xSize"2" ySize"2" xmlnsxsi"http//www
    .w3.org/2001/XMLSchema-instance"
    xsischemaLocation"...factory.xsd"gt
  • ...
  • In Java XML parsers can be triggered to use a
    specific schema.

30
  • ltxsschema xmlnsxs"http//www.w3.org/2001/XMLSch
    ema" elementFormDefault"qualified"gt
  • ltxsinclude schemaLocation"belt.xsd"/gt
  • ...
  • ltxselement name"factory"gt
  • ltxscomplexTypegt
  • ltxssequencegt
  • ltxselement maxOccurs"unbounded"
    ref"location"/gt
  • lt/xssequencegt
  • ltxsattribute name"xSize" use"required"
    type"xsnonNegativeInteger"/gt
  • ltxsattribute name"ySize" use"required"
    type"xsnonNegativeInteger"/gt
  • lt/xscomplexTypegt
  • lt/xselementgt
  • ltxselement name"location"gt
  • ltxscomplexTypegt
  • ltxssequencegt
  • ltxschoice minOccurs"1" maxOccurs"1"gt
  • ltxselement ref"belt"/gt
  • ...
  • lt/xschoicegt

31
Parsing XML
  • In order to parse an XML source youll need
  • javax.xml.parsers.DocumentBuilderFacory
  • A factory creating DocumentBuilders. According
    to the parameters of the
  • factory the generated DocumentBuilder will use
    certain XMLSchemas.
  • javax.xml.parsers.DocumentBuilder
  • This class will parse the input and create a
    Document.
  • the input an element of one of the following
    classes
  • File
  • org.xml.sax.InputSource
  • Reader
  • InputStream
  • String (url)

32
Interface Node
  • An XML document is represented by a tree
    structure, in which each tree node is a class
    implementing the interface org.w3c.dom.Node.
  • important methods
  • String getNodeName()
  • document
  • text
  • user defined tag
  • NamedNodeMap getAttributes()
  • Attr getNamedItem(String name)
  • Node getFirstChild()
  • Node getLastChild()
  • NodeList getChildNodes()
  • int length()
  • Node item(int i)

33
Example
  • document
  • factory
  • text
  • location
  • text
  • floor
  • text
  • text
  • location
  • text
  • floor
  • text
  • walls
  • text
  • text
  • ...

The tree structure of the factory example with
the name of each node.
34
Example in Java
  • factory DocumentBuilderFactory.newInstance()
  • factory.setNamespaceAware(true)
  • factory.setValidating(true)
  • try
  • factory.setAttribute(JAXP_SCHEMA_LANGUAGE,W3C_XML
    _SCHEMA)
  • catch (Exception ex) ...
  • String schema "...factory.xsd"
  • String schemas schema
  • factory.setAttribute(JAXP_SCHEMA_SOURCE,schemas)
  • try
  • builder factory.newDocumentBuilder()
  • catch (Exception ex) ...
  • File f new File("...factory.xml")
  • try
  • document builder.parse(f)
  • catch (Exception ex) ...

35
COSC3P40.xml
  • Package for easy creating and parsing XML code.
  • public interface XMLObject
  • public String toXMLString()
  • public interface XMLNodeConverterltEgt
  • public E convertXMLNode(Node node)

36
COSC3P40.xml.XMLReader
  • public class XMLReaderltEgt
  • private static final String JAXP_SCHEMA_LANGUAGE
  • "http//java.sun.com/xml/jaxp/properties/schema
    Language"
  • private static final String W3C_XML_SCHEMA
  • "http//www.w3.org/2001/XMLSchema"
  • private static final String JAXP_SCHEMA_SOURCE
  • "http//java.sun.com/xml/jaxp/properties/schema
    Source"
  • private DocumentBuilderFactory factory
  • private DocumentBuilder builder null
  • private Document document null
  • private XMLNodeConverterltEgt converter null

37
  • public XMLReader()
  • factory DocumentBuilderFactory.newInstance()
  • factory.setNamespaceAware(true)
  • factory.setValidating(true)
  • try
  • factory.setAttribute(JAXP_SCHEMA_LANGUAGE,W3C_
    XML_SCHEMA)
  • catch (Exception ex)
  • ex.printStackTrace()
  • System.exit(1)
  • public void setXMLSchema(String schema)
  • String schemas schema
  • factory.setAttribute(JAXP_SCHEMA_SOURCE,schemas)
  • try
  • builder factory.newDocumentBuilder()
  • catch (Exception ex)
  • ex.printStackTrace()

38
  • public void setXMLNodeConverter(XMLNodeConverterltE
    gt converter)
  • this.converter converter
  • public E readXML(File f)
  • checkStatus()
  • try
  • document builder.parse(f)
  • catch (Exception ex)
  • ex.printStackTrace()
  • return converter.convertXMLNode(document.getFir
    stChild())
  • ...
  • private void checkStatus()
  • if (buildernull)
  • System.out.println("No XMLSchema set.")

39
COSC3P40.xml.XMLTools
  • Collection of useful (static) methods.
  • public static ListltNodegt getChildNodes(Node node)
  • ListltNodegt result new LinkedListltNodegt()
  • NodeList list node.getChildNodes()
  • for(int i0iltlist.getLength()i)
  • if (!list.item(i).getNodeName().equals("text"))
    result.add(list.item(i))
  • return result
  • public static int getIntAttribute(Node node,
    String name)
  • Attr attr (Attr) node.getAttributes().getNamedI
    tem(name)
  • return Integer.valueOf(attr.getValue())

40
  • public static boolean getBoolAttribute(Node node,
    String name)
  • Attr attr (Attr) node.getAttributes().getNamedI
    tem(name)
  • return Boolean.valueOf(attr.getValue())
  • public static String getStringAttribute(Node
    node, String name)
  • Attr attr (Attr) node.getAttributes().getNamedI
    tem("name")
  • return attr.getValue()
  • public static Enum getEnumAttribute(Class c, Node
    node, String name)
  • Attr attr (Attr) node.getAttributes().getName
    dItem(name)
  • Class array new Class1
  • array0 String.class
  • Object obj null
  • try
  • obj c.getMethod("valueOf",array).invoke(null,
    attr.getValue())
  • catch (Exception e) ...
  • if (obj instanceof Enum) return (Enum) obj

41
Example
  • public class Factory implements XMLObject
  • ...
  • public static Factory load(String fileName)
  • String xsd "../XSD/factory.xsd"
  • XMLReaderltFactorygt reader new
    XMLReaderltFactorygt()
  • reader.setXMLSchema(xsd)
  • reader.setXMLNodeConverter(new
    FactoryReader())
  • return reader.readXML(new File(fileName))
  • ...
  • public String toXMLString()
  • String result "ltfactory xSize\"" xSize
    "\"
  • ySize\"" ySize
    "\"gt\n"
  • for(int i0 iltxSize i)
  • for(int j0 jltySize j)
  • result gridij.toXMLString() "\n"
  • return result "lt/factorygt"

42
  • public class FactoryReader implements
    XMLNodeConverterltFactorygt
  • private LocationReader locReader
  • ...
  • public Factory convertXMLNode(Node node)
  • Factory factory null
  • if (node.getNodeName().equals("factory"))
  • int xSize getIntAttribute(node,"xSize")
  • int ySize getIntAttribute(node,"ySize")
  • Location grid new LocationxSizeySize
  • ListltNodegt list getChildNodes(node)
  • if (list.size() xSizeySize)
  • for(int i0 iltxSize i)
  • for(int j0 jltySize j)
  • gridij
  • locReader.convertXMLNode(lis
    t.get(iySizej))
  • factory new Factory(xSize,ySize,grid)
Write a Comment
User Comments (0)
About PowerShow.com