Pattens in Java
Zhu Liwei
2000.11.15
table of Contents
1. Basic Design Model (Fundamental Design Patterns) ...................................... .......................................... 4
1.1. Delegation (When not to use inheritance) ................................. ........................... 4
1.1.1. Features ........................................... ................................................ ........................... 4
1.1.2. Structure ........................................... ................................................ ........................... 4
1.2. Interface (interface) .......................................... ................................................ ..................... 5
1.2.1. Features ........................................... ................................................ .............................. 5
1.3. Constant (immutable) .......................................... ................................................ .............. 5
1.3.1. Features ........................................... ................................................ .............................. 5
1.3.2. Application: ........................................ ................................................ .............................. 5
1.4. Marker Interface ...................................... ................................................ ... 5
1.4.1. Use ............................................. ................................................ .............................. 6
1.4.2. Structure ........................................... ................................................ .............................. 6
1.5. Proxy .......................................... ................................................ .........................
1.5.1. Description ............................................. ................................................ .............................. 6
1.5.2. Implement ........................................... ................................................ .............................. 6
2. Create a model ...................................... ................................................ ........... 8
2.1. Factory Method .......................................... ................................................ .................. 8
2.1.1. Structure ........................................... ................................................ ............................ 8
2.1.2. Features ............................................. ................................................ ............................ 8
2.2. Abstract factory ........................................ ................................................ 9
2.2.1. Structure ........................................... ................................................ ............................ 9
2.2.2. Features ........................................... ................................................ ............................ 9
2.3. Builder ............................................. ................................................ ................... 10
2.3.1. Structure ............................................. ................................................ .......................... 10
2.3.2. Features ........................................... ................................................ .......................... 102.4. Prototype ................ ................................................ ..................................... 10
2.4.1. Structure ........................................... ................................................ ............................ 11
2.4.2. Features ............................................. ................................................ ............................ 11
2.5. Single instance (Singleton) ........................................... ................................................ ............ 11
2.6. Object pool ........................................ ................................................ .............. 11
2.6.1. Structure ........................................... ................................................ ............................ 11
2.6.2. Features ........................................... ................................................ .......................... 12
3. Segmentation model (Partitioning Patterns) ........................................ ................................................ .........
3.1. Layered Initialization ....................................... .............................................
3.1.1. Structure ........................................... ................................................ ...................................
3.1.2. Features ........................................... ................................................ .......................... 14
3.2. Filter ......................................... ................................................ ...................... 143.2.1. Structure ....................... ................................................ ............................................... 14
3.2.2. Analysis ........................................... ................................................ .......................... 14
3.3. Combination .......................................... ................................................ .................
3.3.1. Structure ........................................... ................................................ .......................... 15
4. Structural model (structural pattern) ........................................ ................................................ .............. 16
4.1. Adapter .......................................... ................................................ ............. 16
4.1.1. Structure ........................................... ................................................ .......................... 16
4.1.2. Features ........................................... ................................................ .......................... 16
4.2. Iterator ......................................... ................................................ ................... 16
4.2.1. Structure ........................................... ................................................ .......................... 16
4.2.2. Features ........................................... ................................................ .......................... 17
4.3. Bridge (Bridge) ........................................ ................................................ ........................ 174.3.1. Structure ....................... ................................................ .................................................... 17
4.3.2. Features ........................................... ................................................ ............................ 18
4.4. Façade .......................................... ................................................ ................. 18
4.5. Flyweight ............................................. ................................................ .......................................
4.5.1. Structure ........................................... ................................................ ............................ 18
4.5.2. Features ............................................. ................................................ ............................ 18
4.6. Dynamic Linkage ...................................... ............................................. 19
4.7. Virtual Proxy ...................................... ................................................ ....... 19
4.8. Decorator ............................................... ................................................ ........................... 19
4.8.1. Structure ........................................... ................................................ .......................... 19
4.8.2. Features ............................................. ................................................ .......................... 19
4.9. Cache Management ........................................ ........................................................................................................... Pattern ............................................. ................................................ ... 20
5.1 Chain of Responsibility ....................................... ............................................ 20
5.1.1. Structure ........................................... ................................................ .......................... 20
5.1.2. Features ........................................... ................................................ .......................... 20
5.2. Command ............................................... ................................................ ......................... 20
5.2.1. Structure ........................................... ................................................ .......................... 20
5.2.2. Features ............................................. ................................................ .......................... 20
5.3. Little Language .......................................... ................................................ .................. 20
5.3.1. Structure ........................................... ................................................ .......................... 20
5.3.2. Features ........................................... ................................................ .......................... twenty one
5.4. Mediator ......................................... ................................................ ................ twenty one
5.4.1. Structure ......................................... ................................................ .......................... 215.4.2. Features ................... ................................................ ................................................ .. twenty one
5.5. Snapshot .......................................... ................................................ .............. twenty one
5.5.1. Structure ........................................... ................................................ .......................... twenty two
5.6. Observer ............................................. ................................................ ......................... twenty two
5.6.1. Structure ......................................... ................................................ .......................... twenty two
5.6.2. Features ........................................... ................................................ .......................... twenty three
5.7. State (state) ........................................ ................................................ ..................... twenty three
5.7.1. Structure ............................................. ................................................ .......................... twenty three
5.7.2. Features ............................................. ................................................ .......................... twenty three
5.8. Null Object) ........................................ ................................................ .......... twenty three
5.8.1. Structure ......................................... ................................................ .......................... twenty three
5.8.2. Features ........................................... ................................................ .......................... 235.9. Strategy ................... ................................................ ................................................ ... twenty four
5.9.1. Structure ........................................... ................................................ .......................... twenty four
5.9.2. Features ............................................. ................................................ .......................... twenty four
5.10. Template Method .......................................... ................................................ ............... twenty four
5.11. Visitor ........................................... ................................................ ............................. twenty four
5.11.1. Structure ........................................... ................................................ .......................... twenty four
5.11.2. Features ........................................... ................................................ .......................... 25
6. Concurrency Patterns ........................................ ................................................ ..... 26
6.1. Single Threaded Execution ...................................... ............................... 26
6.2. Guarded Suspension ..................................... ..................................... 26
6.3. Balking ........................................... ................................................ .............................. 26
6.4. Scheduler ......................................... ................................................ ....... 266.5. Read / Write Lock ............................. ................................................ .............. 26
6.6. Producer - consumer-consumer .................................. ..................................... 26
6.7. Two-phase Termination .......................................... ................................................ ....... 26
1. Basic Design Model (Fundamental Design Patterns)
1.1. Delegation (When not to use inheritance)
Authorization is an extension and multiplexing of a class of functions, that is, use another class with more functions to use an instance of the original class that provides raw functions (Instance).
1.1.1. Features
Advantages: It is wide than inheritance, and can avoid problems that will appear inheritance (inheritance).
i. If an object is a different subclass of a class at different times, then inheritance.
Ii. If a class does not want other classes to see its superclass (Method) or variable (variable), then inheritance.
Iii. If inheritance, superclars will change in the future, which will be risky with the initial time.
IV. Use inheritance, if the superclass (class B) of class A changes, and class A will use class C function, then class A will be wrong.
V. Use inheritance reduces subclasses and superclapping.
Vi. If a class behavior can be determined at runtime, only authorization can be used.
Disadvantages: The use of authorization has no inheritance, and the relationship between classes is not obvious.
In order to make the relationship of authorization more obvious, there are several strategies:
i. Use the name to indicate roles and relationships.
For example, if many classes want to authorize the Widget, these classes can be widgetfactory to reference the authorized object.
II. Use annotations to indicate the purpose of authorization.
III. A class (class a) Do not authorize the class (class b) with another indirect contact (Associate). This is a class B that allows class A to give a direct relationship with it and class B, then class B is authorized to class C.
IV. Using well known design or programming models;
1.1.2. Structure
1.2. Interface (Interface)
If a user class (Client) is provided with the same data and services provided by other plurality of service classes, it can be independent of these service classes through the interface. 1.2.1. Features
Advantages: It can be a class that the user class is independent of the service.
Disadvantages: The program is not easy to understand.
IMMutable
The constant model enhances the robustness of multiple objects that access the same object, reduces the additional overhead of concurrent access objects. After the object is created in this model, you cannot modify any status information. This model does not need to handle synchronization of multiple threads sharing an object.
Suitable for: Multiple objects access multiple instances of the same class, and each instance of this object will change its own status.
1.3.1. Features
advantage:
i. If you do not need a constant model, once the status of an object changes, it is difficult to coordinate between multiple objects of this object, and it is easy to make mistakes. Multiple objects may change the status of the shared object in a different manner.
II. If there are multiple threads share status information of an object, and to change status information, you need to implement synchronization between multiple threads. Additional overhead of thread synchronization increases the additional overhead of access shared target status information, and this extra cost is our unreasonable.
1.3.2. Application:
Be sure to pay attention to the following two points when using this mode:
i. In addition to constructor, there is no method (Method) to modify any variable of an instance (Variable).
II. Any method for calculating new status data must save these new status information into a new instance without changing the status of the same instance.
Expansion: Read Only Object
i. Provides an interface (interface) that includes "get", some users use this interface;
II. Other users can directly use the "GET" and "SET" methods of the class;
1.4. Marking interface (Marker Interface)
The tag interface does not declares any methods or variables, just represents a semantic attribute of a class. It applies to some tool classes. These tool classes draw conclusions from multiple objects, but these operations do not care about the type of object.
E.g:
Two objects equivalent to both objects are judged in Java: COBJECT Equals Method and ==. However, a class only implements the equals method to apply this method in its real case, and == does not have to, but == speed slow, so the preferred Equals, but must know if the class is judged. This method is implemented.
At this time, we can mark the interface Equalbyident, this interface does not have any content, but as long as a class implements the Equale method, it will implement this interface at the same time. By determining that this interface is implemented in a class, you can know if this class implements the Equale method. So we said that Equalbyident only shows the semantic attribute (whether the equals method is implemented).
1.4.1. Use
Extension: The method can be declared in the tag interface.
Note: A class implements a tag interface implies that this class belongs to some type, but also implies all subclasses of this class belong to this type. But it is very likely that subclasses do not implement this tag interface, so measures must be taken:
i. State this class into "Final" and does not allow categories. II. Declare the method to be marked into "final" and is not allowed to be overloaded.
1.4.2. Structure
1.5. Agency (Proxy)
The proxy mode is a method of calling the subject object by proxy object. The class of proxy objects is usually declared that the user object is not allowed to know if they are dealing with an agent.
1.5.1. Description
The basic reason for the use of proxy is to achieve transparent management of services for another object.
There are several universal service management:
i. Make a long time to look like it is completed and returned;
II. Make objects on different machines look like in this machine, this agent is called Remote Proxy for Remote Method Invacation (RMI);
III. Controls access to the available services, this agent is called Access Proxy;
Iv. Make the service object look like an early yield than the actual improvement, which is useful for the service object to create expensive but does not require its service.
1.5.2. Implementation
Let the proxy class and the class that provide services have a common superclass or a common interface.
2. Create a model (Creational Patterns)
2. Factory Method
Making a class that can be used for any data type, this class can instantiate other classes but do not care about other classes. In order to implement this function, this class delegates the task of the selection type to other objects and references the newly created objects through the public interface.
For example: the relationship between applications, documents, and specific document classes.
2.1.1. Structure
Includes the following roles:
Product: Abstract superclass of an instantiated class. Such as Document or Image.
Concrete Product: Instantiated class. If these classes are not public logic, the product can be an interface. Such as
Creator Requestor: To get an instance class.
Factory IF: This interface must be implemented to create a product object for the created requestor (Creator Requestor). It must include a method of creating a request for creating a specific product object. For example, the interface is called DocumentFactoryIF or ImageFactoryIf, where the method used to create is CREATEDOCUMNT or CREATEIMAGE.
Factory Class: A class that implements the factory interface. Such as DocumentFacory or ImageFactory..
2.1.2. Features
Applicable to:
i. Requests Classes with the specific product objects that actually want to create are independent.
II. This product class is dynamic.
2.2. Abstract Factory
It is usually called Kit or Toolkit.
The abstract model provides a method of creating an instance from a set of abstract base classes specified by the corresponding specific subclass. This model is useful because it can be a program running in multiple complex external portions, such as different window systems with similar functions.
2.2.1. Structure
User (Client): This class is requested and accepted from its running system with a variety of components (Widget) classes. User classes can only see abstract parts classes, and see the specific components. AbstractFactory: Abstract factory defines an abstract method for creating a specific component class, which is usually called getFactory or getToolkit. User class calls This method can get an instance of a specific factory, which is used to create specific components relative to a particular product.
ConcreteFactoryXX: This class implements its abstract factory-defined methods to create specific component class instances. Although the user class is called a specific factory method, it actually accesses an example of their abstract factory class, and the user class does not know the existence of specific factory classes.
Parts (Widgetxx): This is an abstract class that is equivalent to a feature of a specific subclass of their specific subclasses.
Product Components (ProductXWidgetxx): is a specific component of a product, a feature of a product.
2.2.2. Features
advantage:
i. Specific components and use and initialize their classes are independent because abstract factory classes encapsulate the processing of creating part objects;
Ii. It is easy to expand;
Iii. You can use the specific product by the characteristics of the category through the product;
Disadvantages:
Extended workload is large.
2.3. Builder (Builder)
The Builder Model allows a user object to construct this object as long as it indicates the type and content of a complex object, and can construct this object, and the user is separated from the object constructed.
2.3.1. Structure
Product: This role defines a series of data representatives, all product classes must implement the ProductIF interface so that other classes can access product objects through this interface without knowing a product object class.
Productif: The interface that must be implemented.
User (Client): User object transmits data information to the getInstance method of AbstractBullder, which returns an instance of a subclass of AbstractBullder. The user object passes the instance to the build method of the Director object, this method creates a desired object.
Concrete Builder: It is a specific subclass of an abstract generator to generate a specific type of data representative of the Director object.
Abstract Generator: This class wants to define a method typically called GetInstance, one of which is used to specify the data representative. Abstract generators also define some methods for generating a portion of an object. The final abstract generator will define a method that is usually called getProduct, returns the generated product object.
Director: Director object calls the method of the specific generator object, providing the content of the product object for the specific generating gas.
2.3.2. Features
advantage:
i. Content decisions are opposite to each other with a specific data object.
Ii. You can create better control, because Director can be created step by step, while other models are created one step.
Disadvantages:
The implementation and use of a large number of general methods are difficult. 2.4. Prototype
The prototype model can create custom objects without knowing the class or how it is created. It passes the object of the prototype to the object of the object to create initial values.
2.4.1. Structure
User Class: The user class is a class to create an object, which has a method of joining the object to the user object, which is usually called REGISTERPROTOTYPE or REGISTERSYMBOL.
Prototype: Implement the prototyperif interface, which is instantiated in order to be replicated by the user.
PrototyPebuilder: Prototype Generator creates prototype objects to transmit prototype objects to user objects. Applicable to any class of an object. Usually has a name that indicates the prototype object type that it creates, such as Symbulbuilder.
2.4.2. Features
advantage:
i. You can add and delete prototype objects during runtime, which is no other creation mode.
Ii. A prototype generator can easily provide a fixed series of prototype formations. At the same time, it can also be flexible to use object portfolios to join the value of the object that may be created and changing the object attribute.
Iii. User objects can create new prototype object types.
IV. User objects are independent of the exact class of objects it wants to create.
v. Prototyperbuilder encapsulates the details of building prototype objects.
Vi. By enforcing an interface like prototypeif like prototype object, prototype system ensures that prototype objects provide a consistent way to user objects.
insufficient:
i. Many times are used to write original generator classes.
II. Programs that use prototype models typically use dynamic connection or similar mechanisms so that the installation of the program is complicated.
2.5. Single instance (Singleton)
Single Example Model Make sure that only one instance is created, all objects using this class use the same instance.
2.6. Object Pool
If the cost of creating an object is large or there is a limit to the number of objects, the object pool model can be used.
2.6.1. Structure
Reusable: The instance of this role class is limited to the time of the cooperation between other objects, and then disconnects this cooperation.
User (Client): Using the instance of the class of the Reusable object.
ReusablePool: This class's instance manages the user class for Reusable, which usually saves all of the Reusable now not used in the same object pool, which can be managed by a consistent proxy. Therefore, ReusablePool is a class that is a single instance (Singleton). ReusablePool can also limit the number of Reusable objects.
2.6.2. Features
advantage:
i. Applicable when the request for the object is changed.
II. The object and creating separate management form a more closely designed, eliminating interactions with implementation of implementation and management capabilities and management classes.
Disadvantages:
i. If there is a lot of request to the object, there is a performance problem.
II. When the order is reached, the request cannot be processed immediately, and it is necessary to wait.
3. Segmentation Model (Partitioning Patterns 3.1. Layered Initialization)
If you need a number of abstract implementations, you typically define all public logic, and then define some special logic of some subclass packages. But if public logic is used to decide which special subclass created, the above method is not easy to use.
Suitable for data comparison, data must be processed before deciding which specific class is instantiated.
3.1.1. Structure
Services: All kinds of cooperation in the layered initialization model are to provide the same services. Services class provides services in two ways.
i. For objects outside the mode, the instance of the service class is the only visible in the model.
Ii. Service class encapsulates public logic of various situations, which entrusts specific parties in public operations to classes that implement the serviceIMPLIF interface.
Once the service class instance collected all the information necessary to create a specific object that implements the serviceIMPLIF interface, it will pass these information to the ServiceImplfactory object responsible for creating a specific object.
If you want the service class to be reused, you need a static method setFactory to set the serviceImplfactory object, which can be used by all instances of the service class.
If you don't want to multiplex the service class, you don't need setFactory, or you don't need serviceImplfactoryif.
ServiceImplif: The service object accesses a specific object via this interface.
ServiceImplfactoryif: The service object uses this interface to access the ServiceImplfactory object.
ServiceImplxx: These classes implements the serviceImplif interface to provide specific logic required for the service class.
3.1.2. Features
advantage:
i. If the data used by an object needs to be analyzed before this object initialization, the initialization process of this object is very complicated, and the layered initialization makes the user object awareness of this complicated.
Ii. User objects are only deal with the service objects in the hierarchical initialization, and other classes in this model are independent.
3.2. Filter (FILTER)
The filter model allows the object to perform unused conversion and calculations on the data stream, or can have a dynamically connected interface to perform any operation of the data stream.
3.2.1. Structure
The filter model divides the class into a data source (Data Sinks), Data Filter.
Abstract source: This abstract class has a method getData for returning data.
ConcrectionSource: It is a subclass of an abstract source for providing data instead of conversion and analysis of data.
Abstract Source Filter: It is a superclass with a class that converts and analyzes data. Its constructor has a parameter, which is an example of an abstract data source, and an abstract source filter is obtained by this instance. Since the abstract source filter is also a subclass of an abstract source, the data receiver is the same as the specific source is like a particular source. The abstract source filter also defines a getData method, just calling the getData method of the abstract source object from which it consists.
ConcrectionSourceFilter: It is a subclass of an abstract source filter, which extends the getData method of abstract filters, and implements corresponding conversion and analysis operations. Abstract Data Receiver (AbstractSink): An instance of an abstract data receiver calls the getData method for the abstract source.
Similar to a model of Senddata.
3.2.2. Analysis
advantage:
i. Structural is good.
Ii. Filters are generally designed to be independent of specific procedures, which improves the reuse.
insufficient:
Filters are generally designed to be independent of specific procedures, sometimes because they cannot affect performance in some context-related information.
3.3. Combination (Composite)
Also called the recursive combination model.
The combined model allows you to combine similar objects into complex objects by recuing similar trees. By requiring all objects in a tree having the same superclass or interface, the combination model allows an operation to be consistent with the object of the tree.
3.3.1. Structure
Abstract Parts: It is an abstract class that is a common super class that makes up all objects in the object tree of a combined object.
ConcreteComponentxx: The leaves of the trees tissue.
AbstractComposite: It is an abstract superclass of all combinations in a combined model. The abstract combination defines and provides a method of providing a part of the management combined object. Such as Add, Remove, GetIld, etc.
ConcreteCompositivexx: An example of these classes is a combined object using other instances of abstract parts.
4. Structural model (Structural Patterns)
4.1. Adapter
The adapter implements an interface known by the user, allowing users to access an instance of the class it doesn't know. The adapter implements the functionality of the interface, but does not care what kind of category implementation this interface.
4.1.1. Structure
User (Client): This class calls another class by an interface so that it does not need to know which particular class is used to call the method.
Targetif: This interface declares a method of user class calls.
Adapter: This class implements a Targetif interface. It implements a method that invokes the AdapteE class by calling this method, and Adaptee does not implement a TargetIF interface.
Adaptee: Adaptee does not implement a Targetif interface, just includes a method called by a user class.
4.1.2. Features
advantage:
i. User class and Adaptee are independent of each other.
II. You can decide the method of calling an object with an adapter class.
Disadvantages:
Make the program difficult to understand.
4.2. Iterator (Iterator)
The iterator model defines an interface to sequentially access the object in the combination. Through such an interface access set makes the accessed class and the class of the interface independently.
4.2.1. Structure
Collection: This class encapsulates a national object or value.
Iterator Interface (Iteratorif): This interface defines the method of sequential access to the objects in the collection.
Iterator: A iterator interface.
Combined interface (CollectionIF): Collection is responsible for creating their own iterator objects, for convenience, should be created in a consistent manner. So all the set classes must implement a collection interface (CollectionIF), declare a method to create an iterator object in the interface. 4.2.2. Features
advantage:
i. You can access the collection object without knowing the data source.
II. Using an iterator object, you can have a sequence of the objects in multiple collections.
4.3. Bridge (Bridge)
Bridge models have an abstract level and corresponding implementation. The bridge model does not combine abstract and implementation into many distinct classes, but to be implemented with each other, these classes can be dynamically bonded.
4.3.1. Structure
In order to achieve the purpose of separation of abstraction and implementation, the abstract class can be accessed through the interface, and the hierarchical layers of these interfaces are parallel to abstract layers.
Abstraction: This class represents the highest level of abstraction, which is responsible for maintaining a reference to an object of an abstract implementationImpl interface to delegate the operation to that object. If an instance of this class is also an example of its subclass, this instance will also reference objects that implement the corresponding sub-interfaces of the AbstractImpl interface.
Specialized: This is a subclass of abstraction. Each subclass has a corresponding sub-interface for AbstractionImpl. A specific abstract class also entrusts its operation to the object that implements the corresponding sub-interface of AbstractImpl.
Abstraction IMPL: This interface declares a method of all underlying operations that must be provided by abstraction.
Specialized (Specialize): This is a sub-interface of abstractionImpl. Each SpecializedabStractionImpl corresponds to a SpecializedAbStraction, declares that all the underlying operations required for the implementation of the class.
Implement XX (IMPLXX): These classes implements the Abstract IMPL interface, providing different implementations of abstract classes.
Specific implementation XX (SpecializedImplxx): Each class implements a SPECIALIZEDABSTRActionIMPL interface that provides a different implementation of the SpecializeDabstraction class.
4.3.2. Features
advantage:
i. Abstraction and implementation of each other.
II. Users of abstract classes do not have to care for specific implementations, so changing implementations do not affect user classes.
4.4. Outer (Façade)
The Façade model is simplified to access a set of related objects, and the method is to provide an object, and all objects outside of this group can communicate with this object with this object.
4.5. Flyweight
If a plurality of instances containing the same information can be interactive, the Flyweight model allows a program to avoid waste of multiple instances containing the same information by sharing an object.
4.5.1. Structure
AbstractFlyWeight: It is a superclass for all other FlyWight classes that define all the common operations of all Flyweight classes that get the external status information of the Flyweight class by parameters. SharedConcreteflyweight: The instance of these classes is a shared object. If they contain any intrinsic state, this status must be common in all entities represented by each instance.
UnsharedConcreteflyWeight: The instance of these classes is unable to share. If the unable to share object is AbstractFlyWeight instance, then these objects are often an example of the AbstractFlyWeight different subclasses.
FlyWeightFactory: FlyweightFactory: Example of the AbstractFlyWeight class is provided by the user. If the user class requests an instance of the class of unsharedConcreteflyWeight, FlyWeightFactory just creates this instance, but if the request is an instance of a sharedconcreteflyweight class, FlyweightFactory's instance will check if the previously created object, if there is this The object is returned to the user, otherwise it will create new.
User (Client): User class instance uses the Flyweight object.
4.5.2. Features
advantage:
Reduce the number of objects in memory.
insufficient:
i. Make the procedure complicated, mainly because the Flyweight object with an external state is required, and the reuse of the Flyweight object is also managed.
II. Increase the running time of the program, because accessing the external state is more than the internal state fee.
III. Usually different individuals can be identified by different objects, but the Flyweight model cannot be, because the same object represents multiple entities.
IV. Shared Flyweight objects cannot include a parent pointer.
Because the complexity of the Flyweight model and the limit for class organizations, this model is suitable for optimization after design.
4.6. Dynamic Linkage
Make the program to load and use any class that implements a known interface.
4.7. Virtual Proxy
If the price of an object is very large, it may be useful to delay the initialization to determine that this object is required. The virtual proxy model allows the user to access the required objects through a proxy that implements the same interface as the user needs, so that users don't know that the object has not actually existed, this technique is sometimes called Lazy Instantiation.
4.8. Decorator
Also called the Wrapper model.
The Decorator model extends the object's functionality to the user's transparent manner, and the method is an instance of subclasses of the initial class, and this instance is delegated to the initial object.
4.8.1. Structure
Abstract Services: The Decorator model can extend the functionality of the service object, and the abstract service is the public superclass of all of these that may be extended. Sometimes this role is an interface.
Concreteservice: The Decorator model extends ConcretService by authorizing an instance of a ConcretService class.
Abstract packaging (AbstractWrapper): It is a superclass of all packaging classes, which is responsible for maintaining references to service objects authorized by packaging objects. This class typically overloads all methods of the abstract service class. ConcretewrapPerxx: These classes extend the features of AbstractWrapper.
4.8.2. Features
advantage:
Flexible than inheritance.
There is less than inheriting.
insufficient:
easy to make mistake.
There are many objects that are generated, not easy to debug.
It is not easy to mark the service object with an object identity because the service object may be hidden by the Wrapper object.
4.9. Cache Management
The buffer management model can access faster access takes a long time to access objects. Such objects create a large cost, and after a requirement for this object, it saves the copy of the object.
5. Behavioral Patterns
5.1. Chain of Responsibility
The responsible chain model allows an object to handle commands without knowing what object is accepted. The method is to pass the command to an object chain. This object chain is usually part of a large structure. Each object in the chain may handle the command, or transfer the command to the next object in the chain, or process and down. .
5.1.1. Structure
A commandsender: CommandSender puts the command to the first object in the object chain of the command command, usually call the POSTCOMMAND method for calling the CommandHandler.
Processing the commander: CommandHandler is a superclass for all objects in the object chain of the command. It has two methods: handlecommand and postcommand.
ConcreteCommandrandlerxx: These classes process commands.
5.1.2. Features
advantage:
i. Reduce the contact between the objects of the command and the object of the processing command.
Ii. You can handle the command more flexible.
insufficient:
i. You cannot guarantee that all commands can be processed.
Ii. If the object in the liability chain is too much, it will become a problem.
5.2. Command
Pack the command into the object so you can choose, sort, query, undo, and other operations.
5.2.1. Structure
Abstract command (AbstractCommand): This role class is a superclass for all classes that encapsulate commands, which defines at least the DOIT method, and the undoot method is defined if needed.
ConcreteCommand: This role is a specific class that encapsulates a specific command. Other classes call this command through DOIT, by calling UndoIT recovery.
Callor (Invoker): This class creates a command object and calls the DOIT or undoot method of the command object.
Command Manager: The Command Manager is responsible for managing the command object created by the caller.
5.2.2. Features
advantage:
i. Provides flexibility in the sorting of TIMING and commands.
Ii. It is easy to add new commands.
5.3. Little Language
If you need to solve many similar problems, and notice that these can be solved with different combinations of elements or operations, then the simplest way to solve these problems is to define a small language (Little Language). The problem that can be solved with a small language is usually the search, the creation of complex data structures, and formatted.
5.3.1. Structure
User (Client): This class is running a small language program and provides the data required to this program, using the result of the program. The user instance is also created a parser instance, and the user instance provides data to the program via the input stream object, the parser instance resolves the program. The PARSE method of the parser object returns a ABSTRACTNONTERMINAL instance, which is the root of the parsing tree. User object calls the Execute method of the Abstractnonterminal object.
Lexical Analyze: Once the parse method of the parser object is called, it creates a LexicalanalySer object reads the character from the same input stream object to it, using the vocabulary rule to identify the terminator, when the parser calls the vocabulary When analyzing the NEXTTOKEN method of the object, these identified symbols are returned.
Analyzer (PARSER):
Abstractnonterminal: The object of subclass of this class can be used as a node that parsing the tree.
Concretenonterminalxx: These classes can be used as nodes for parsing the tree.
TerminalToken: This abstract class has no variables and methods, which is equivalent to the terminator of vocabulary analysis identification.
InputStream: An instance of this class is used to read a character stream.
5.3.2. Features
i. Little Language model allows users to specify a combination of different operations.
Ii. Language is a user interface, you can know which easy, which is easy to use by using it or see others.
5.4. Mediator
The Mediator model uses an object to coordinate the status of other objects, which is logically tighter and reduces the connection between other objects.
5.4.1. Structure
COLLEAGUEXX: There are two dependence on the instance of this role, there are two dependencies:
An object requires the consent of other objects that must be adjusted before doing some state changes;
An object is required to inform other objects after the state changes;
These two dependencies are similar, and the instance of Colleaguexx is associated with the same Mediator object, which is licensed by the Meidator object, and also notifies other objects through this Mediator object.
EventListenerxx: These interfaces make Colleaguexx higher reuse. The existence of the interface makes Colleaguexx don't know the existence of the Meidator object. Each interface defines a method related to a particular event. You can complete the status notification as long as the corresponding method of calling the corresponding interface, without knowing the Mediator object that implements this method.
Mediator: Mediator instance handles status notifications from Colleaguexx to implement the EventListener interface. Mediator instances also need to define some methods, and Colleaguexx calls these methods to connect themselves and Mediator objects such as RegisterColleague.
5.4.2. Features
advantage:
i. Management complexity Transfer from other objects to MeiaTory objects, which is easy to implement and maintain; II. Putting a series of object dependencies to make these dependency logic more easily understood. Therefore, if the Mediator object is too large, divide this object into multiple objects is also easy to understand.
III. Using Mediator objects often means that these classes are not necessary to implement dependencies of the Colleague class.
IV. Colleague class is more reused because it is not necessary to perform dependencies, because the code of dependency processing is usually related to a particular application.
Disadvantages:
Because dependent code is usually related to a particular application, the Mediator class is usually not multiplexed.
5.5. Snaphoto (Snapshot)
Another model called MEMENTO is similar to this model and similar.
Snapshot saved (Snapshot), so that the status of this object can be restored later. Objects for saving and recovering status do not need to know specific status information, it only needs to know whether objects that are saved and recovered have implemented a specific interface.
5.5.1. Structure
There are two structures, one is a non-permanent copy of an object state with a MEMENTO object.
The originator (Originator): The status of this class will be saved and restored, calling its CreateMemento method to create a MEMENTO object that includes status information of the originatory object. Later, if you want to recover the status of the Originator object, you can pass this Memento object to the SetMEMEMEMENTO method.
MEMENTO: It is the private static class of the Originator class to implement the MEMENTOIF interface. It encapsulates the snapshot of the Originator object state.
MEMENTOIF: ORIGINATOR access to the MEMENTO object via the MEMENTOIF interface. This MEMENTO interface usually does not declares the method, if any method, these methods can also change the status of the package. This ensures consistency and integrity of the status of the package.
Caretaker: This class instance saves a collection of MEMENTO objects. Once a MEMENTO object is created, this object is usually added to a collection. If you want to do a UNDO action, the Caretaker object works with other objects to select a MEMENTO object, then call the SetMemento method of the selected object to restore its status.
Another structure is serialized,
Target: ObjectOutputStream object transitions the instance status of the Target class into byte stream, ObjectInputStream restores the instance status of the Target class from this byte stream, which is completely passive in these action, ObjectOutputStream and ObjectInputStream objects are completed. All work.
ObjectOutputStream: This class objects discovers status information that accesses a Target object, which is written together with information along with the information required to recover.
OutputStream: If status information needs to be stored indefinitely, OutputStream will be a FileoutPutStream. If these status information only need to be saved to the end of the program, OutputStream may just be a BYTEARRAYOUTPUTSTREAM.
ObjectInputStream: This class reads the serialized status information from the byte stream and restores them. Comparison of these two structures:
Serialization MEMENTO persistence can be easily saved in the overall state of the memory that cannot be implemented, especially when an object includes some other object's state, the simple object, etc., the simple object, etc., the simple object, etc., can not get one absolutely the same Objects can achieve additional overhead when creating a snapshot of an object in memory. There is no special additional overhead expertise requires a mechanism for serialization. There is no special need.
5.6. Observer
This model allows the dependence of the registration object between the object to be dynamically, so that other objects depending on the status of this object.
5.6.1. Structure
Observerif: This interface defines a method that is usually called Notify or Update. The OBServer object calls this method to provide a notification of its state change and pass it appropriately parameters. In many cases, the reference to OBSERVABLE objects is usually one of the parameters so that the method knows what objects provide notifications.
Observer: This class's object implements the OBServerIF interface to accept status change notifications from OBSERVABLE.
Observableif: ObservableIf: Observable object implements this interface, this interface defines two methods to allow OBSERVABLE object registration and logout acceptance notifications.
Observable: This class implements the OBServableIF interface, which is responsible for managing the login of ObservableIf to the receiving state change. Observable does not implement these, but entrusts to a Multicaster object.
Multicaster: This class's instance manages the registration of the OBServeriF object, which is transmitted to OBServerif on behalf of the OBSERVABLE object. Enter these responsibilities to Multicaster objects allows them to achieve all OBSERVABLE objects that implements the same OBSERVABLEIF interface or to transmit notifications to the same OBServerif.
5.6.2. Features
advantage:
The transmission of the notification can be carried out in the case where the transmit object and the acceptance object do not know each other.
Disadvantages:
i. If a change in an object needs to notify a lot of other objects, the transmission of the notification takes a long time.
Ii. In the case of cyclic dependencies, the stack overflow will appear.
Iii. If a notification can be sent to other threads asynchronously, then the situation will be complicated.
IV. An Observer object receives a notification that only knows that object changes, but can't know how to change.
5.7. State (state)
Pack the status of an object into a separate object, each object belongs to a different subclass of an abstract state class.
5.7.1. Structure
Context: This instance of this class is displayed.
ContextState: This class is a superclass for all classes that represent the status of the Context object. This class usually defines these methods:
START: Completes the initialization of the status management object, returns an object equivalent to the initial state of the user object.
ProcessEvent: It is an abstract method that has a parameter indicating an event of an event, returns a new current state. Each subclass of ContextState is to overload the ProcesseEvent method in a manner that corresponds to the status representative, and the ProcesseEvent implements an exit from the previous state.
Enter: Before the start and processEvent method returns, call the Enter method first, this method performs the inlet action before entering a state. OperationXX: These methods implements a unique action for each state.
ContextState defines the name constant to define the name constant for event code to pass to ProcessEvent.
ConcreteStatexx: is a subclass of ContextState, which must implement the ProCessevent method.
5.7.2. Features
advantage:
The code in each state is in its own class, which can easily complete the new state without side effects. For this reason, the State model is suitable for a lot of status.
5.8. Null Object
The NULL Object model provides a choice, which is to use null to indicate that the object part you want to delegate, so that this object must be NULL before using the entrusted object. In order not to NULL, the NULL OBJECT model applies a reference to an object that pointing to anything.
5.8.1. Structure
Delegator: This class delegates an operation to an abstract class or an interface. This class is not responsible for anything that does not do anything, it just assumes that it is entrusted to encapsulate the correct operation, even if nothing is .
AbstractOperation: Delegator entrusts the operation to AbstractOperation. This role can be a class or an interface.
REALOPERATION: This role is a class that implements Delegator.
NullOperation: This role is the operation of the Delegator's delegated operation.
5.8.2. Features
advantage:
i. Because a class delegates the operation to other classes, this class does not have to be responsible for achieving that operation. Thus, before the method is called, it is not necessary to judge whether the object is NULL before the method of the implementation of the entrusted operation, which further reduces the chance of BUG due to no judgment.
II. If you don't do anything with all Delegator classes, what is not done by the NullOperation package is being reused.
Disadvantages:
Added the number of classes.
5.9. Strategy
Pack the relevant algorithm into the class, these classes have the same superclass. This allows the algorithm to change as the object, and changes over time.
5.9.1. Structure
User (Client): This role is delegated to an abstract class or interface, and it does not know the actual class of the object it entrusted, and this object if this is implemented.
AbstractStrategy: This role is a generic way for accessing its subclass package. This role can also be an interface.
Concretestrategyxx: This role class provides a variety of implementations of the CLIENT.
5.9.2. Features
advantage:
i. This model allows dynamic to determine the behavior of the Client object.
II. Simplified Client objects by reducing the choice of client object selection and implementation.
Template Method
Write an abstract class that includes no part of the logic to achieve the desired purpose. The remaining logic is achieved by subclasses of this class.
5.11. Visitor
Some operations require a lot of objects in the structure to participate, a method of implementing this operation is to provide this operation in all types that support this operation. The Visitor model provides another way: putting the necessary logic to a separate Visitor class, which simplifies many categories in this complex structure. The Visitor model can also change logic by using different Visitor classes. 5.11.1. Structure
Including two models, the first is an ideal model that can produce a relatively clean result, but unfortunately do not apply in many cases. The application of the second model is relatively wide, but the dependence between the classes is increased.
a) the first one:
User (Client): An instance of this role class is responsible for an object of a Russian object structure and an object in which it uses the Concretevisitor object to operate the object structure.
ObjectStructure: An instance of this role class as the root of an object structure. When accessing objects in an object structure, the Visitor object begins with an instance of ObjectStructure, and then moves to other objects in the object structure. In the Visitor model, allowing a class as both the ObjectStructure role and as a ConcreteElement role.
Abstractractlement: This role is an abstract superclass of all objects that make up object structure. It defines an abstract method such as Accept, this method uses an AbstractVisitor object as its parameters. The subclass of AbstractElement provides this method, which is to call the AbstractVisitor object, then pass this AbstractVisitor object to the Accept method of other AbstractElement objects.
ConcenteelementXX: This example of this role is an element of an object structure, and the ConcreteElement object is calculated by passing the AbstractVisitor object to the ACCETEEEEMent's AcceptElement. The ACCEPT method passes the ConcreteElement object to an AbstractVisitor object so that this AbstractVisitor object is calculated to the ConcreteElement object. Once the calculation is completed, the ConcreteElement object passes the AbstractVisitor object to another ConcreteElement object. Accept method
Visitor: This role class is a superclass of all classes that are calculated in the object structure. It defines a method that allows the instance of each class to be accessed to pass them yourself to the Visitor object included in their computing.
Concretevisitor: An instance of the class of this role includes an object structure.
The above model applies to all Visitro objects accesses the elements in the object structure along the same path. It is the advantage of making the Visitor class independent of the object structure. But it is not applicable in both cases.
i. Visitor will modify the object structure.
Ii. If the object structure is very large, Visitor only needs to access a small portion of it.
b) Another model:
In this model, the Visitor class is responsible for navigating their own access path. The advantage of this model is to modify the object structure or by the selected navigation. However, the virtual Visitor class of this model cannot be reused because the Visitor class knows the structure of an object structure in order to implement navigation. In this model, the Abstractlement column is not oriented about the method of Visitor object, and the Visitor class defines the method of its subclass for navigation.
5.11.2. Features:
i. Simplify the process of adding a new operation to an object structure.
Ii. This model focuses on a Concretevisitor class, so it is easy to maintain.
Disadvantages:
i. ConcreteElement must provide a sufficient self-state required for Visitor calculations, which means that some types of packages need to be hidden.
II. Join the new ConcreteElement class in the object structure.
6. Concurrent model (Concurrency Patterns)
6.1. Single Threaded Execution
Critical section
advantage:
i. The method of ensuring class is thread-safe.
Disadvantages:
i. If you need to protect the time, it will reduce performance.
Ii. It is easy to have a deadlock.
6.2. Surveillance Suspension
Hang a way to call the execution until a prerequisites are met.
advantage:
i. Using this model can allow a thread to process an object that is in an incorrect operation of an operation. It just waits until this object is in the correct state, not the synchronization lock of this object.
II. Can be used to control the same method for multiple threads to apply the same object.
Disadvantages:
Can't be used for nested synchronization.
6.3. BALKING
If the status of the object is not suitable for performing a method, then this method is called, then this method is nothing to do.
6.4. Scheduler
This object will give the waiting threads to be sorted by the order of threads scheduled by a single-threaded code. The scheduler provides a mechanism for implementing a scheduling policy, but it is independent of any specific scheduling policy.
advantage:
i. A way to directly control the thread to perform a piece of code.
II. Scheduling strategy is packaged in a separate class is multiplexed.
Disadvantages:
Additional expenses increased more than direct calls.
6.5. Read / write lock (Read / Write Lock)
Objects can be read, but it is necessary to write a write operation.
6.6. Producer - consumed, consumer-consumer
Control information or asynchronous production and consumption of objects.
6.7. Two-Phase Termination
Advantages to the orderless shutdown thread or process through a latch. Threads or processes are required to check the value of the latch in key points.