1 / 85

Creational Design Patterns

Creational Design Patterns. Factory Method Abstract Factory Builder Prototype Singleton Object Pool. CDP - Factory Method. Synopsis: Need for a class for reuse with arbitrary data types.

liesel
Télécharger la présentation

Creational Design Patterns

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Creational Design Patterns Factory Method Abstract Factory Builder Prototype Singleton Object Pool

  2. CDP - Factory Method Synopsis: Need for a class for reuse with arbitrary data types. Reusable class remains independent of the classes it instantiates by delegating the choice of which class to instantiate to another object and referring to the newly created object through a common interface. Context: Creates a framework to support instantiations of various data types.

  3. CDP - Factory Method Forces: Provide services (methods) in a way transparent to classes using those services. Solution: Proxy object and the service providing object must either be instances of a common super class or implement a common interface. Consequences: Could introduce new failure points.

  4. CDP - Factory Method - Example You have an application such as MS Office. You want to perform some common functions with all the files. Example of common functions might be open file, save file, etc. The only difference is that the functions are done on different file types such as word doc files, excel xls files and PowerPoint ppt files. You could write several independent functions for each of the different types but the code would be very similar with only the data type as a difference. The factory method allows you to build a framework to perform the common functions with only a few classes that reused for each type.

  5. CDP - Factory Method - Example Manage Doc Files doc file commands Manage Xls Files xls file commands Manage Ppt Files ppt file commands file commands Manage Files Make one Function

  6. CDP - Factory Method - Example edits Document 1 Application * MyDocument May be doc, xls, or ppt.

  7. CDP - Factory Method - Example edits Document 1 Application * Requests creation creates DocumentFactoryIF MyDocument DocumentFactory

  8. CDP - Factory Method - Example Suppose you have a process which reads and writes a DataStream to a socket. Write to Socket stream string Socket Read from Socket stream string Socket But you also wish to have strings in which you encrypt the data. And you write an encrypted DataStream and read back an encrypted Data Stream decrypt it.

  9. CDP - Factory Method - Example encrypted stream encrypted string Write to Encrypted Socket EncryptedSocket encrypted stream string encrypted string Encrypt Data Write to Encrypted Socket EncryptedSocket encrypted stream encrypted string decrypted string Read from Socket Decrypt Data Socket But now you realize that there are several different encryption algorithms and codes you wish to use.

  10. CDP - Factory Method - Example The process to encrypt differs in using many different different algorithms (function/method) and type of string output must be written for each type. encrypted stream encrypted String #1 Encrypt Data Write to Encrypted Socket string EncryptedSocket algorithm # 1 encrypted stream encrypted String #2 Encrypt Data Write to Encrypted Socket string EncryptedSocket algorithm # 2 encrypted stream encrypted String #n Encrypt Data Write to Encrypted Socket string EncryptedSocket algorithm # n

  11. CDP - Factory Method - Example The factory pattern allows you to have a framework that will handle any type of algorithm and encrypted data. concrete product encrypted stream encrypted String Encrypt Data Write to Encrypted Socket string EncryptedSocket algorithm # 1 algorithm # n algorithm # 2

  12. CDP - Factory Method - Example Socket Socket 4 6 Product encrypt, decrypt 1 Encryption EncryptedSocket EncryptedSocket 1 * Creation Requester DESEncryption 1 5 * Transcription Concrete Product * creates 1 creates 1 EncryptionFactory 3 Factory * requestCreation EncryptionFactoryIF Interface 2

  13. Socket Encryption EncryptedSocket encrypt, decrypt 1 1 * DESEncryption * Transcription * creates 1 EncryptionFactory creates 1 EncryptionFactoryIF * requestCreation CDP - Factory Method - Example import java.io.InputStream; import java.io.IOException; import java.io.OutputStream; import java.net.Socket; import java.security.Key; import java.security.NoSuchAlgorithmException; // This class extends socket to encrypt the stream of bytes over the net. public class EncryptedSocket extends Socket { private static Encryption crypt; private Key key;

  14. CDP - Factory Method - Example Socket Encryption EncryptedSocket encrypt, decrypt 1 1 * DESEncryption * Transcription * creates 1 EncryptionFactory creates 1 EncryptionFactoryIF * requestCreation // Constructor // @param Key for encryption and decryption. // Determines encryption technique by calling key object's getAlgorithm() method. // @param Factory object to use to create Encryption objects. // @exception NoSuchAlgorithmException if key specifies technique not available. public EncryptedSocket(Key key, EncryptionFactoryIF factory) throws NoSuchAlgorithmException { this.key = key; crypt = factory.createEncryption(key); } // Constructor(Key, EncryptionFactoryIF)

  15. CDP - Factory Method - Example // Returns an input stream that decrypts the inbound stream of bytes. // @return an input stream for reading decrypted bytes // @ IOException if an I/O error occurs when creating the input stream. public InputStream getInputStream() throws IOException { return crypt.decryptInputStream(super.getInputStream()); } // getInputStream() // Returns an output stream that encrypts the outbound stream of bytes. // @return an output stream for reading decrypted bytes // @IOException if an I/O error occurs when creating the output stream. public OutputStream getOutputStream() throws IOException { return crypt.encryptOutputStream(super.getOutputStream()); } // getOutputStream() } // class EncryptedSocket

  16. CDP - Factory Method - Example Socket Encryption EncryptedSocket encrypt, decrypt 1 1 * DESEncryption * Transcription * creates 1 EncryptionFactory creates 1 EncryptionFactoryIF * requestCreation import java.io.InputStream; import java.io.OutputStream; import java.security.Key; // Abstract class to encrypt/decrypt streams of bytes. abstract public class Encryption { private Key key; // * Constructor * @param key The key to use to perform the encryption. public Encryption(Key key) { this.key = key; } // Constructor(Key) // * Return the key this object used for encryption and decryption. protected Key getKey() { return key; } // getKey()

  17. CDP - Factory Method - Example // This method returns an OutputStream. // It encrypts bytes written to it. // And it writes the encrypted bytes to the given OutputStream. // @param out OutputStream that OutputStream returned writes encrypted bytes. abstract OutputStream encryptOutputStream(OutputStream out); // This method returns an InputStream. // It decrypts the stream of bytes read from the given InputStream. // @param in InputStream that InputStream returned reads bytes. abstract InputStream decryptInputStream(InputStream in); } // class Encrypt

  18. CDP - Factory Method - Example Socket Encryption EncryptedSocket encrypt, decrypt 1 1 * DESEncryption * Transcription * creates 1 EncryptionFactory creates 1 EncryptionFactoryIF * requestCreation import java.security.Key; import java.security.NoSuchAlgorithmException; // This interface must be implemented by all factory classes // that are used to create instances of subclasses of Encryption. public interface EncryptionFactoryIF { // Returns an instance of appropriate subclass of Encryption. // The instance is determined from information provided by the given Key object. // @param key will be used to perform the encryption. public Encryption createEncryption(Key key) throws NoSuchAlgorithmException; } // interface EncryptionFactoryIF

  19. CDP - Factory Method - Example Socket Encryption EncryptedSocket encrypt, decrypt 1 1 * DESEncryption * Transcription * creates 1 EncryptionFactory creates 1 EncryptionFactoryIF * requestCreation import java.security.Key; import java.security.NoSuchAlgorithmException; // This class creates instances of appropriate subclasses of Encryption. //The appropriate subclass is determined by calling the Key object's public class EncryptionFactory {

  20. CDP - Factory Method - Example Socket Encryption EncryptedSocket encrypt, decrypt 1 1 * DESEncryption * Transcription * creates 1 EncryptionFactory creates 1 EncryptionFactoryIF * requestCreation // Returns an instanace of the appropriate subclass of Encryption. // It is determined by the given Key object's getAlgorithm method. // @param key The key that will be used to perform the encryption. public Encryption createEncryption(Key key) throws NoSuchAlgorithmException{ String algorithm = key.getAlgorithm(); if ("DES".equals(algorithm)) return new DESEncryption(key); if ("RSA".equals(algorithm)) return new RSAEncryption(key); throw new NoSuchAlgorithmException(algorithm); } // createEncryption(Key) } // class EncryptionFactory

  21. CDP - Factory Method - Example Socket Encryption EncryptedSocket encrypt, decrypt 1 1 * DESEncryption * Transcription * creates 1 EncryptionFactory creates 1 EncryptionFactoryIF * requestCreation import java.io.InputStream; import java.io.FilterInputStream; import java.io.FilterOutputStream; import java.io.OutputStream; import java.security.Key; // class to DES encrypt/decrypt streams of bytes. public class DESEncryption extends Encryption { /** * Constructor * @param key The key to use to perform the encryption. */ public DESEncryption(Key key) {super(key); } // Constructor(Key)

  22. CDP - Factory Method - Example Socket Encryption EncryptedSocket encrypt, decrypt 1 1 * DESEncryption * Transcription * creates 1 EncryptionFactory creates 1 EncryptionFactoryIF * requestCreation // Returns an OutputStream that encrypts the bytes written to it/ // And writes the encrypted bytes to the given OutputStream. // @param out OutputStream that OutputStream returned by this method writes encrypted bytes. OutputStream encryptOutputStream(OutputStream out) { return new DESEncrytpedOutputStream(out); } // encryptOutputStream(OutputStream)

  23. CDP - Factory Method - Example Socket Encryption EncryptedSocket encrypt, decrypt 1 1 * DESEncryption * Transcription * creates 1 EncryptionFactory creates 1 EncryptionFactoryIF * requestCreation /** * This method returns an InputStream that decrypts the stream of * bytes that it reads from the given InputStream. * @param in The InputStream that the InputStream returned by this * method will read bytes from. */ InputStream decryptInputStream(InputStream in) { return new DESEncrytpedInputStream(in); } // decryptInputStream(InputStream)

  24. CDP - Abstract Factory Method Synopsis: Need for a class for reuse with abstract classes. Reusable class remains independent of the classes it instanciates by delegating the choice of which class to instanciate to another object and referring to the newly created object through a common interface. Context: Creates a framework to support instanciations of various abstract classes.

  25. CDP - Abstract Factory Method Forces: Provide services (methods) in a way transparent to classes using those services. Solution: Proxy object and the service providing object must either be instances of a common super class or implement a common interface. Consequences: Could introduce new failure points.

  26. CDP - Abstract Factory Method Suppose you have a textfield or any other GUI component and you wish to display it on a particular platform. Display windows textfield

  27. CDP - Abstract Factory Method Suppose you wish to display those GUI components on various platforms. Display windows textfield MacOS textfield Linix textfield Certainly each platform expects to see different Java byte code.

  28. CDP - Abstract Factory Method Request services Client 1 uses uses Abstract Factory CPU Architecture Toolkit uses Concrete Factory creates EmberCPU Concrete Product EmberToolkit EnginolaCPU * creates EnginolaToolkit * MMU creates 1 EmberMMU EnginolaMMU requestCreation

  29. CDP - Abstract Factory Method // Sample client class shows how a client class can create concrete widget objects using an abstract factory public class Client { public void doIt () { ArchitectureToolkit af; af = ArchitectureToolkit.getFactory(ArchitectureToolkit.EMBER); CPU cpu = af.createCPU(); //... } //doIt } // class Client

  30. CDP - Abstract Factory Method // Abstract factory class for creating objects for remote tests on computer components. public abstract class ArchitectureToolkit { private static final EmberToolkit emberToolkit = new EmberToolkit(); private static EnginolaToolkit enginolaToolkit = new EnginolaToolkit(); //... // Symbolic names to identify types of computers public final static int ENGINOLA = 900; public final static int EMBER = 901; // ...

  31. CDP - Abstract Factory Method // Returns a concrete factory object as an instance of the concrete factory class. // It is appropriate for the given computer architecture. // @param architecture - value indicating architecture that concrete factory returned for. static final ArchitectureToolkit getFactory(int architecture) { switch (architecture) { case ENGINOLA: return enginolaToolkit; case EMBER: return emberToolkit; // ... } // switch String errMsg = Integer.toString(architecture); throw new IllegalArgumentException(errMsg); } // getFactory()

  32. CDP - Abstract Factory Method // Method to create objects for remote testing CPUs. public abstract CPU createCPU() ; // Method to create objects for remote testing MMUs. public abstract MMU createMMU() ; //... } // ArchitectureToolkit

  33. CDP - Abstract Factory Method // This is a concrete factory class for creating objects used to perform remote tests. // These tests are on core components of ember architecture computers. class EmberToolkit extends ArchitectureToolkit { // Method to create objects for remote testing ember CPUs. public CPU createCPU() { return new EmberCPU(); } // createCPU() // Method to create objects for remote testing ember MMUs. public MMU createMMU() { return new EmberMMU(); } // createMMU() //... } // class EmberToolkit

  34. CDP - Abstract Factory Method // This is a concrete factory class for creating objects used to perform remote tests. // These tests are on core components of enginola architecture computers. class EnginolaToolkit extends ArchitectureToolkit { // Method to create objects for remote testing enginola CPUs. public CPU createCPU() { return new EnginolaCPU(); } // createCPU() // Method to create objects for remote testing enginola MMUs. public MMU createMMU() { return new EnginolaMMU(); } // createMMU() //... } // class EnginolaToolkit

  35. CDP - Abstract Factory Method // This is an abstract class for objects that perform remote tests on CPUs. public abstract class CPU extends ComponentTester { //... } // class CPU // This is an abstract class for objects that perform remote tests on CPUs. public abstract class CPU extends ComponentTester { //... } // class CPU

  36. CDP - Abstract Factory Method // Class for objects that perform remote tests on Ember architecture CPUs. class EmberCPU extends CPU { //... } // class EmberCPU // Class for objects that perform remote tests on Enginola architecture CPUs. class EnginolaCPU extends CPU { //... } // class EnginolaCPU

  37. CDP - Abstract Factory Method // This is an abstract class for objects that perform remote tests on MMUs. public abstract class MMU extends ComponentTester { //... } // class MMU _________________________________________________________________________ // Class for objects that perform remote tests on Enginola architecture MMUs. class EnginolaMMU extends MMU { //... } // class EnginolaMMU _________________________________________________________________________ // Class for objects that perform remote tests on Ember architecture MMUs. public class EmberMMU extends MMU { //... } // class EmbeMMU

  38. CDP - Builder Synopsis: Need to build an instance of an object depending on the type of instance needed. Context: Allows a client object to construct a complex object by specifying only its type and content. Forces: Program required to produce multiple external representations of the same data.

  39. CDP - Builder Solution: Abstract Builder builds and returns the data representation needed. Concrete builder, subclass of abstract builder, used to build a specific kind of data representation. Consequences: Provides finer control over construction that other patterns.

  40. CDP - Builder Suppose you have an e-mail gateway program. The program receives a message in MIME format and forwards them in a different format for a different kind of e-mail system. MIME mail Forward E-mail format 1 Destination 1 format 2 Destination 1 format n Destination 1 You have a procedure (set of methods) for each format builder routine. The methods are similar but you need multiple procedures. The builder pattern allows you to use one method for all formats.

  41. CDP - Builder You want a class to build the format needed depending on the Destination using a builder class. MIME mail format whatever Build Format Forwarded E-Mail Destination 1 Destination 1 Destination 1

  42. CDP - Builder 1: receive(MIME) Director manages MessageManager MIMEMsg sends 2: parse(MIME) ProductIF is parsed by OutboundMessageIF 4: send MIMEParser PRoFMsg * directs MAPIMsg Product 3: build * MessageBuilder creates 1 creates PROFSBuilder MAPIBuilder requestCreation

  43. CDP - Builder (collaboration diagram) 2: parse(MIME) 1: receive(MIME) 1.1: outMsg:=parse(msg:MIMEMsg) MIMEParser 1: receive (msg:MIMEMsg) MessageManager 1.2: send( ) 1.1.2: to(:String) 1.1.3:from(:String) 1.1.4:plainText(:String) 1.1.5:jpegImage(:Image) 1.1.6:outMsg :=getOutboundMsg( ) outMsg:OutboundMessageIF 4: send 1.1.1: builder:=getInstance(to:String) Builder:MAPIBuilder MessageBuilder 3: build

  44. 1: receive (msg:MIMEMsg) 1.1: outMsg:=parse(msg:MIMEMsg) MIMEParser MessageManager 2: parse(MIME) 1: receive(MIME) 1.2: send( ) 1.1.2: to(:String) 1.1.3:from(:String) 1.1.4:plainText(:String) 1.1.5:jpegImage(:Image) 1.1.6:outMsg :=getOutboundMsg( ) outMsg:OutboundMessageIF 4: send 3: build Builder:MAPIBuilder 1.1.1: builder:=getInstance(to:String) MessageBuilder CDP - Builder import java.awt.Image; // This is an abstract builder class for building e-mail messages abstract class MessageBuilder { // Return an object of the subclass for the e-mail message format implied by the destination address. //@param dest The e-mail address the message is to be sent to static MessageBuilder getInstance(String dest) { MessageBuilder builder = null; //... return builder; } // getInstance(String)

  45. CDP - Builder // pass the value of the "to" header field to this method. abstract void to(String value); // pass the value of the "from" header field to this method. abstract void from(String value); //... // pass the value of the "organization" header field to this method. void organization(String value) { } // pass the content of a plain text body part to this method. abstract void plainText(String content); // pass the content of a jpeg image body part to this method. abstract void jpegImage(Image content) ; // complete and return the outbound e-mail message. abstract OutboundMessageIF getOutboundMsg() ; } // class MessageBuilder

  46. CDP - Builder // Class used to represent raw MIME e-mail messages. // If program expanded to receive messages in formats other than MIME, // then this will probably become an abstract class with a subclass for each type of e-mail. public class MIMEMessage { private byte[] rawMessage; // Constructor @param msg A byte array containing a raw unprocessed e-mail message. public MIMEMessage(byte[] msg) { rawMessage = msg; } // constructor(byte[]) // Return the raw bytes of an unprocessed e-mail message. byte[] getMessage() { return rawMessage; } // getMessage() } // class MIMEMessage

  47. CDP - Builder 1: receive (msg:MIMEMsg) 1.1: outMsg:=parse(msg:MIMEMsg) MIMEParser MessageManager 2: parse(MIME) 1: receive(MIME) 1.2: send( ) 1.1.2: to(:String) 1.1.3:from(:String) 1.1.4:plainText(:String) 1.1.5:jpegImage(:Image) 1.1.6:outMsg :=getOutboundMsg( ) outMsg:OutboundMessageIF 4: send 3: build Builder:MAPIBuilder 1.1.1: builder:=getInstance(to:String) MessageBuilder import java.awt.Image; // This is a class to parse MIME e-mail messages. class MIMEParser { private MIMEMessage msg; // The message being parsed private MessageBuilder builder; // The builder object //...

  48. CDP - Builder // parse MIME message, call builder methods for message's header fields and body parts. OutboundMessageIF parse(MIMEMessage msg) { this.msg = msg; builder = MessageBuilder.getInstance(getDestination()); MessagePart hdr = nextHeader(); while (hdr != null) { if (hdr.getName().equalsIgnoreCase("to")) builder.to((String)hdr.getValue()); else if (hdr.getName().equalsIgnoreCase("from")) builder.from((String)hdr.getValue()); //... hdr = nextHeader(); } // while hdr

  49. CDP - Builder MessagePart bdy = nextBodyPart(); while (bdy != null) { if (bdy.getName().equals("text/plain")) builder.plainText((String)bdy.getValue()); //... else if (bdy.getName().equals("image/jpeg")) builder.jpegImage((Image)bdy.getValue()); //... bdy = nextHeader(); } // while body return builder.getOutboundMsg(); } // parse(MIMEMessage) private MessagePart nextHeader() { MessagePart mp = null; //... return mp; } // nextHeader()

  50. CDP - Builder private MessagePart nextBodyPart() { MessagePart mp = null; //... return mp; } // nextBodyPart() // return the destination e-mail address for the message private String getDestination() { String dest = null; //... return dest; } // getDestination()

More Related