1 / 25

Java Design Patterns

Java Design Patterns. Java Design Patterns. Object Pool Filter Virtual Proxy Snapshot. All these patterns are from: “Patterns In Java(TM)” by Mark Grand. Object Pool. Synopsis

Download Presentation

Java 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. JavaDesign Patterns SD

  2. SD Java Design Patterns Object Pool Filter Virtual Proxy Snapshot All these patterns are from: “Patterns In Java(TM)” by Mark Grand

  3. SD Object Pool Synopsis Manage the reuse of objects when a type of object is expensive to create or only a limited number of objects can be created. Context Why not reuse objects? Re-initialize only part of the object’s state. Limited resource A variation of a singleton. Forces A program may not create more than a limited number of instances for a particular class. If creating instances of a particular class is expensive, then creating new instances for that class should be avoided. A program can avoid creating some objects by reusing objects when it has finished with them rather than discarding them as garbage.

  4. SD Structure Object Pool (cont’)‏ Manage Reusable Objects 0..* Client 1 Manager These are stereotypes 1 ReusablePool <<constructor>> -ReusablePool <<misc>> +getInstance()‏ +acquireReusable():Reusable +releaseReusable(:Reusable)‏ +setMaxPoolSize(maxSize:int)‏ ... Uses ▼ 1 * Reusable 0..*

  5. SD Object Pool (cont’)‏ Participants Reusable Collaborate with other objects for a limited amount of time. Client Use Reusable objects. ReusablePool Manage Reusable objects for use by Client objects. Usually, it’s desirable to keep all Reusable objects not currently used in the same object pool. To achieve this, the ReusablePool class is designed to be singleton class.

  6. SD Object Pool (cont’)‏ Consequences Advantages: Avoid need for object creation. Works best when the demand for objects doesn’t vary greatly over time. Keeping the logic to manage the creation and reuse of a class’s instances in a separate class from the class whose instances are being managed results in a more cohesive design. Disadvantages: When demand varies greatly. The object pool is a bottleneck. Still need to do some initialization on used objects to make them “fresh” Implementation Storage use an array for bounded number of objects and a Vector for an unbounded number. Creation the ReusablePool object should be the only object able to create Reusable objects

  7. SD Object Pool (cont’)‏ Code Example consider a database connection class public class Connection { private final static ConnectionImpl.ConnectionPool connectionPool = ConnectionImpl.ConnectionPool.getInstance(); private String databaseName; … Object sendRequest(Request request) { Object result; ConnectionImpl impl; impl = connectionPool.acquireImpl(databaseName); result = impl.sendRequest(request); connectionPool.releaseImpl(impl); return result; } } class ConnectionImpl { … Object sendRequest(Request request) { … } }

  8. SD Object Pool (cont’)‏ Code Example (cont’)‏ static class ConnectionPool { private static ConnectionPool thePool = new ConnectionPool(); private Hashtable poolDictionary = new Hashtable(); private ConnectionPool(); public static ConnectionPool getInstance() { return thePool; } public synchronized ConnectionImpl acquireImpl(String dbName) { Vector pool = (Vector)poolDictionary.get(dbName); if (pool != null) { int size = pool.size(); if (size > 0)‏ return (ConnectionImpl)pool.remove(size-1); } // no ConnectionImpl in pool, so create one. return new ConnectionImpl(dbName); } public synchronized void releaseImpl(ConnectionImpl impl) { ... } }

  9. SD Object Pool (cont’)‏ Related Patterns Cache Management another object management scheme Factory method doesn’t manage objects after their creation Singleton objects that manage object pools are usually singletons the objects in the object pool imply a limited (more than 1) number of instances of a certain class.

  10. SD Filter Synopsis Allow objects that perform different transformations and computations on s and have compatible interfaces to dynamically connect in order to perform arbitrary operations on streams of data. The Java IO library provides this extensively. Context Stream decorators... count no. of bytes coming through stream. CAPITALIZE LETTERS. cipher/decipher A uniform interface and composability

  11. SD Filter (cont’)‏ Forces Classes that implement common data transformations and analyses are used in a great variety of programs. It should be possible to dynamically combine data analysis and transformation objects by connecting them together. The use of transformation/analysis objects should be transparent to other objects. Structure AbstractSourceFilter AbstractSource AbstractSink create(AbstractSource)‏ getData()‏ getData()‏ Gets-data-from Gets-data-from ConcreteSourceFilter ConcreteSource create(AbstractSource)‏ getData()‏ getData()‏

  12. SD Filter (cont’)‏ Participants AbstractSource declares a method that returns data when it’s called. ConcreteSource subclass of AbstractSource, primarily responsibe for providing data rather than transforming or analyzing. AbstractSourceFilter Superclass of classes that transform and analyze data. delegates fetching of data to AbstractSource object. ConcreteSourceFilter extend behavior of inherited getData method to perform appropriate transformation or analysis operation. AbstractSink call getData method of AbstractSource. Same pattern can be used on the Data Sink

  13. SD Filter (cont’)‏ Consequences Advantages: The portion of a program that follows the Filter pattern is structured as a set of sources, sinks and filters. Filter objects that don’t maintain internal state can be dynamically replaced while the program is running. Allows dynamic change of behavior and adaptation to different requirements at runtime. It’s quite reasonable for a program to incorporate both forms of the Filter pattern. However, it is unusual for the same class to participate in both forms Implementation Zero knowledge Filter classes should be implemented in a way that doesn’t assume anything about programs/classes - should have no side effects. This promotes reusability. Knowledgeable filters sometimes zero knowledge can hamper performance, consider methods for providing context-specific information. Anyway - this is a trade-off

  14. SD Filter (cont’)‏ Java API usage class java.io.FilterReader concrete classes: BufferedReader FileReader LineNumberReader Code Example consider the InStream example: public abstract class InStream { public abstract int read(byte[] array) throws IOException; } public class FileInStream extends InStream { private RandomAccessFile file; public FileInStream(String fName) throws IOException { file = new RandomAccessFile(fName,”r”); } public int read(byte[] array) throws IOException { return file.read(array); } }

  15. SD Filter (cont’)‏ Code Example (cont’)‏ public class FilterInStream extends InStream { private InStream inStream; public FilterInStream(InStream inStream) throws IOException { this.inStream = inStream; } public int read(byte[] array) throws IOException { return inStream.read(array); } } public class ByteCountInStream extends FilterInStream { private long byteCount = 0; public ByteCountInStream(InStream inStream) throws IOException { super(inStream); } public int read(byte[] array) throws IOException { int count; count = super.read(array); if (count > 0)‏ byteCount += count; return count; } public long getByteCount() { return byteCount; } }

  16. SD Filter (cont’)‏ Code Example (cont’)‏ public class TranslateInStream extends FilterInStream { private byte[] translationTable; private final static int TRANS_TBL_LENGTH = 256; public TranslateInputStream(InStream inStream, byte[] table) throws IOException { super(inStream); translationTable = new byte[TRANS_TBL_LENGTH]; System.arraycopy(table,0,translationTable,0, Math.min(TRANS_TBL_LENGTH, table.length)); for (int i = table.length; i < TRANS_TABLE_LENGTH; i++) { translationTable[i] = (byte)i; } } public int read(byte[] array) throws IOException { int count; count = super.read(array); for (int i = 0; i < count i++) { array[i] = translationTable[array[i]]; } return count; } }

  17. SD Filter (cont’)‏ Related Patterns Composite can be an alternative when objects involved do not have a consistent interface and they can be composed statically. Decorator Filter is a special case of the Decorator pattern. Pipe Layered Architecture

  18. SD Virtual Proxy Synopsis Lazy instantiation. Context plugablility can use new classes at runtime. They only have to support a given interface. Extendability you may add new features (probably using composition of primitive features) to an existing application.

  19. SD Virtual Proxy (cont’)‏ Forces It is very time consuming to instantiate a class. It may not be necessary to instantiate the class. Instantiating a number of instances at once may introduce a noticeable delay in program response managing delayed instantiation should not be burdened on the class’s clients. Structure Uses <<interface>> ServiceIF Client ServiceHelper1 operation1()‏ operation2()‏ Uses Uses ServiceProxy ServiceHelper2 Creates operation1()‏ operation2()‏ Service operation1()‏ operation2()‏ Uses

  20. SD Virtual Proxy (cont’)‏ • Participants • Service • provides the required service. • instantiates other helper classes upon creation. • Client • uses the Service through the ServiceProxy • ServiceProxy • delays creation of Service objects. • may implement some of the ServiceIF methods without using a concrete Service instance. • When needed, instantiates the Service class and delegates methods to the Service instance • ServiceIF • defines the interface to the Service, which is duplicated in the ServiceProxy

  21. SD Virtual Proxy (cont’)‏ • Consequences • Advantages: • instances of classes accessed by the rest of the program exclusively through a virtual proxy are not created until they are needed. • Classes that use the proxy do not need to be aware of whether the Service class is loaded, whether an instance of it exists, or whether the class even exists. • Disadvantages: • All classes other than the proxy must access the service class indirectly through the proxy. • Implementation • consider packing the pattern in a package and only exposing the Proxy class.

  22. SD Virtual Proxy (cont’)‏ Code Example consider the CabinetAssistant example: public class CabinetAssistant implements CabinetAssistantIF { public CabinetAssistant(String s) { … } public void operation1() { … } … } public interface CabinetAssistantIF { public void operation1(); … } public class CabinetAssistantProxy { private CabinetAssistantIF assistant = null; private String myParam; public CabinetAssistantProxy(String s) { myParam = s; }

  23. SD Virtual Proxy (cont’)‏ Code Example (cont’)‏ private CabinetAssistantIF getCabinetAssistant() { if (assitant == null) { try { Class clazz = Class.forName(“CabinetAssistant”); Constructor constructor; Class[] foramlArgs = new Class[] ( String.class }; constructor = clazz.getConstructor(formalArgs); object[] actuals = new Object[] { myParam }; assistant = (CabinetAssistant)‏ constructor.newInstance(actuals); } catch (Exception e){ } if (assistant == null) { throw new RuntimeException(); } } return assistant; } public void operation1() { getCabinetAssistant().operation1(); } … }

  24. SD Virtual Proxy (cont’)‏ Related Patterns Facade can be used with the virtual proxy to minimize number of proxy classes needed. Proxy the virtual proxy is a specialized version of the Proxy pattern.

  25. SD Snapshot Synopsis An extension of the memento pattern. Taking a snapshot of the state of system objects. Context serialization Save/Load in a role-playing game. Forces you need to create a snapshot of an object’s state and also be able to restore the state of the object. you want a mechanism that saves & restores an object’s state to be independent of the object’s internal structure. Changing internal structure shouldn’t change save/restore mechanism.

More Related