Design Pattern Summary: Structural model (bottom)

Source: Internet
Author: User
Tags deprecated

In general, design patterns fall into three broad categories:
Create Five types of models: Factory method mode, abstract Factory mode, singleton mode, builder mode, prototype mode.
structure mode , a total of seven kinds: Adapter mode, adorner mode, proxy mode, appearance mode, bridging mode, combined mode, enjoy the meta-mode.
There are 11 types of Behavioral patterns : Strategy mode, template method mode, observer mode, iteration sub-mode, responsibility chain mode, Command mode, Memo mode, state mode, visitor mode, mediator mode, interpreter mode.
In fact, there are two types: concurrency mode and thread pool mode.
Several structural models have been introduced earlier: Design pattern Summary: Structural model (upper)

Four, the appearance mode (Fasade)

appearance mode: provides a consistent interface for a set of interfaces in a subsystem, and the facade schema defines a high-level interface that makes this subsystem easier to use.
After the appearance role is introduced, the user only needs to interact directly with the appearance role, and the complex relationship between the user and the subsystem is implemented by the appearance role, thus reducing the coupling of the system.
That is to provide a facade class to unify the operation subsystem, which is suitable for the complicated situation of subsystem.

The main problem is: there is too much coupling between the various complex subsystems of the component's customers and components, and this excessive coupling is challenged by many changes as the external client program and subsystems evolve.
As an example:
For example, now that we have a car that we (the client program) wants to start, we have to launch the engine (subsystem 1) and turn the Four wheels (subsystem 2). But in practice we don't need to push the wheels with our hands to make them turn, we step on the accelerator, and then the car rotates the wheels according to some other operation. Throttle is like the system to leave us the interface, no matter how the car is to turn the wheel, the wheel change into what brand, we have to take the car to do or to step down the accelerator.
effects after using the appearance mode:

class Diagram:

among the roles involved are :
appearance role (facade): is the core of the pattern, he is called by the customer client role, know the functions of each subsystem. Several functional combinations are also booked according to the existing requirements of the customer's role.
subsystem Role (Subsystem classes): Implements the functions of the subsystem and processes tasks assigned by the facade object. For subsystems, the facade and client roles are unknown and do not have any relevant information about the facade; that is, there is no instance pointing to facade.

Code:

//SUBSYSTEM classClass SubClass1 {voidOperation1 () {System.out.println ("SubClass1 operation1"); }}class SubClass2 {voidOperation2 () {System.out.println ("SubClass2 operation2"); }}class SUBCLASS3 {voidOperation3 () {System.out.println ("SubClass3 Operation3"); }}//Appearance classClass Facade {SubClass1 subClass1;    SubClass2 SubClass2; SUBCLASS3 SUBCLASS3; Public facade() {SubClass1 =NewSubClass1 (); SubClass2 =NewSubClass2 (); SUBCLASS3 =NewSUBCLASS3 (); } Public void Method() {subclass1.operation1 ();        Subclass2.operation2 ();    Subclass3.operation3 (); }}//User classClass Client { Public void Dosth() {Facade facade =NewFacade ();    Facade.method (); }}

Applicable occasions:
1) When it is necessary to provide an external simple interface for the complex subsystem to be used by the user, the subsystem tends to become more and more complex because of the continuous evolution; When some users do not need to customize the subsystem, facade can provide the user with a default view to use, when there are other users who need to be customized, You can customize it over facade, which is common in open-source projects, such as retrofit.
2) in order to avoid the large dependence of client programs and abstract classes, the introduction of facade to separate subsystems from customers and other subsystems can improve the independence and portability of subsystems.
3) Reduce the coupling between subsystems; When you need to build a hierarchy of subsystems, use the facade pattern to define the entry points for each layer in the subsystem. If subsystems are interdependent, you can make the subsystems communicate only through facade, simplifying their dependencies.

advantages and disadvantages of the facade model:
Advantages:
1) Loose coupling: The façade mode is loosely coupled between the client and subsystem, allowing the modules inside the subsystem to be more easily extended and maintained
easy to use: the façade mode makes the subsystem more user-friendly, the client no longer needs to understand the implementation of the subsystem internal, and does not need to track the internal modules of multiple subsystems to interact, just to interact with the façade class can be
Better classification of access levels: by using facade rationally, we can help us to better classify the level of access. Some methods are external to the system, and some methods are used internally by the system. The need to expose external functions to the façade, which is convenient for the client to use, but also a good way to hide the internal details.
Disadvantages:
1) It is not very good to restrict the use of subsystem classes, and if you make too many restrictions on the client Access subsystem class, you reduce variability and flexibility.
2) without introducing abstract appearance classes, adding new subsystems may require modifying the source code of the Appearance class or client, violating the "open and closed principle".

Reference Blog: http://blog.csdn.net/u013256816/article/details/51009480

V. Bridging mode (BRIDGE)

intention: to separate the abstract and the implementation parts so that they can be independently changed.
Application Scenario: separating abstraction from implementation
Imagine that if you want to draw a rectangle, circle, ellipse, square, we need at least 4 shape classes, but if the drawing needs to have a different color, such as red, green, blue, etc., at this time at least the following two design scenarios:
The first design is to provide a set of various colors for each of the shapes.
The second design is to combine shapes and colors according to actual needs
For a system with two changing dimensions (that is, the reason for two changes), the number of classes in the design system is less, and the system expansion is more convenient. Design Scheme Two is the application of bridge mode. Bridging mode transforms inheritance relationships into associations, reducing the coupling between classes and classes, and reducing the amount of code written.
class Diagram:

To achieve the above case:

//Abstraction abstract classAbstractClass IShape {protectedIcolor color; Public IShape(Icolor color) { This. color = color; }Abstract voidOperation ();}//Implementor Implementation class interfaceAbstractClass Icolor {Abstract voidOperationimpl ();}//Concreteimplementor Specific implementation classClass Colorred extends icolor{@Override    voidOperationimpl () {System.out.print ("Color is Red"); }}class Colorblue extends icolor{@Override    voidOperationimpl () {System.out.print ("Color is Blue"); }}//Refinedabstraction Extensions abstract classClass Rectangle extends IShape { Public Rectangle(Icolor color) {Super(color); }@Override    voidOperation () {System.out.print ("It is a rectangle");    Color.operationimpl (); }}class Oval extends IShape { Public Oval(Icolor color) {Super(color); }@Override    voidOperation () {System.out.print ("It is a Oval");    Color.operationimpl (); }}//cient use classClass Client { Public void dotest() {IShape shape1 =NewRectangle (NewColorred ()); IShape Shape2 =NewOval (NewColorblue ());        Shape1.operation ();    Shape2.operation (); }}

Advantages and Disadvantages:
1) Advantages:
Detach the abstract interface and its implementation part.
Bridging mode is sometimes similar to multiple inheritance schemes, but multiple inheritance schemes violate the single principle of responsibility of a class (that is, a class has only one reason for change), reusability is poor, and the number of classes in multiple inheritance structures is very large, bridging mode is a better solution than multiple inheritance schemes.
Bridging mode improves the scalability of the system, and it does not need to modify the original system to extend the dimension in two changing dimensions.
The implementation details are transparent to the customer, and the implementation details can be hidden from the user.
2) Disadvantages:
The introduction of bridging mode will increase the difficulty of system understanding and design, because the aggregation correlation relationship is based on the abstraction layer, which requires the developer to design and program the abstraction.
Bridge mode requires the correct identification of two independent changes in the system of the dimensions, so its scope of use has some limitations.

Applicable environment:
If you do not want to use a fixed binding relationship in the abstraction and implementation section, you can use bridging mode to separate the abstraction from the implementation, and then dynamically set the specific implementation to be used during the program's operation and dynamically switch the specific implementation.
If the abstract and implementation parts should be able to expand the situation, you can use the bridge mode, so that the abstract part and the implementation part can be independently changed, so that can be flexibly expanded independently, rather than stirred together, the extension side will affect the other side.
If you want to implement part of the modification, will not affect the customer, you can use the bridge mode, the client is an abstract interface in the run, the implementation of some of the changes, can be independent of the abstract part, it will not affect the customer, it can be said that the customer is transparent.
If the implementation of the inheritance will lead to a lot of subclasses, in this case, you can consider bridging mode, analyze the reasons for functional changes, see if it can be separated into different latitude, and then separated by bridging mode, thereby reducing the number of subclasses.

Vi. combination Mode (Composite)

concept: combine objects into a tree structure to represent a "partial-whole" hierarchy. Combining patterns makes it unique for users to use individual objects and composite objects.
application: The typical application of combinatorial mode is
1) file directory structure
2) ViewGroup and view in Android

Applicability: The combined mode decouples the internal structure of the client and complex elements, allowing the client program to handle complex elements as simple elements.
If you want to create hierarchies and can treat all the elements in the same way, then the combined pattern is the ideal choice.
1) represents the part of an object-the overall hierarchy, such as a tree menu, a folder menu, a departmental organizational structure, and so on.
2) The user ignores the combination object and the individual object, the user will uniformly use all the objects in the composite structure.
class Diagram:

Involved roles:
1) Component: Is the object declaration interface in the composition, and, where appropriate, implements the default behavior for all classes of common interfaces. Declares an interface for accessing and managing component.
2) Leaf: The leaf node object is represented in the composition, and the leaf node has no child nodes.
3) Composite: Defines the behavior of the branch node, which is used to store the sub-parts and to implement operations related to the subassemblies in the component interface, such as additions and deletions.
Code:

AbstractClass Component {protectedString name; Public Component(String name) { This. name = name; }Abstract voidOperation ();Abstract voidAdd (Component Component);Abstract voidRemove (Component Component);AbstractComponent Getchild (inti);} Class Leaf extends Component { Public Leaf(String name) {Super(name); }@Override    voidOperation () {SYSTEM.OUT.PRINTLN ("Leaf"+ name); }@Deprecated    voidAdd (Component Component) {}@Deprecated    voidRemove (Component Component) {}@DeprecatedComponent Getchild (inti) {return NULL;}} Class Composite extends Component {arraylist<component> childs; Public Composite(String name) {Super(name); Childs =NewArraylist<> (); }@Override    voidOperation () { for(Component child:childs) child.operation (); }@Override    voidAdd (Component Component) {childs.add (Component); }@Override    voidRemove (Component Component) {childs.remove (Component); }@OverrideComponent Getchild (inti) {returnChilds.get (i); }}class Client { Public void dotest() {Component LEAF1 =NewLeaf ("LEAF1"); Composite com =NewComposite ("Composite");        Com.add (LEAF1); Com.add (NewLeaf ("Leaf2")); Composite COM2 =NewComposite ("Composite2"); Com2.add (NewLeaf ("L3"));    Com2.add (COM); }}

Advantages and Disadvantages:
Advantages:
1) A hierarchical complex object can be clearly defined to represent all or part of an object, making it easier to add new artifacts.
2) client invocation is simple, and the client can consistently use a composite structure or a single object within it.
3) defines a class hierarchy that contains Leaf objects and container objects, and the leaf objects can be combined into more complex container objects, and the container objects can be combined so that they can be recursively handed down to form complex tree structures.
4) It is easier to join the object widget in the composition, and the client does not have to change the original code because it joins the new object widget.
Cons: making the design more abstract, and if the business rules of an object are complex, it is challenging to implement a composite pattern, and not all methods are associated with leaf object subclasses

Seven, enjoy the meta-mode (FlyWeight)

background: Object-oriented can be very convenient to solve some extensibility problems, but in this process the system must produce some classes or objects, if there are too many objects in the system, it will cause the system performance degradation. The simplest and most straightforward way to solve this problem is to reduce the number of objects in the system.
The enjoy meta-mode provides a solution for reusing the same or similar objects using shared technologies. This means that code sharing for the same or similar objects is implemented.
The most typical application in Java is string:

"a""a";System.out.println(s1 == s2);// String采用享元模式 存储在常量池

definition: uses shared technology to effectively support the reuse of large numbers of fine-grained objects. The system uses only a small number of objects, and these objects are very similar, the state changes very small, you can achieve multiple reuse of objects. Because the enjoy meta mode requires that the object that can be shared must be a fine-grained object, it is also known as lightweight mode, which is an object-structured pattern.
Concept: We need to understand two concepts before we understand the meta-mode: internal state, external state.
Internal state: the shared part that is not changed within the enjoyment meta object as the external environment changes.
External state: The state that cannot be shared is an external state as the environment changes.
because the enjoy meta-mode distinguishes between internal and external states, we can set different external states so that the same objects can have some different characteristics, and the internal state is set to the same part. In our program design process, we may need a large number of fine-grained objects to represent the object, if these objects in addition to a few parameters, the other parts are the same, this time we can use the enjoy meta-mode to greatly reduce the objects in the application. How do you use the enjoy meta model? Here we just need to move the different parts of their few parts as arguments to the outside of the class instance, and then pass them over when the method is called. Here's a point: the internal state is stored inside the enjoy meta object, while the external state should be considered by the client.

There are two ways to enjoy the meta-model: The simple-to- enjoy meta -mode and the complex-enjoy meta -mode two forms;
(a) simply enjoy the META mode:
In the simple-to-enjoy mode, all the objects of the object can be shared.
class Diagram:

Involved roles:
Flyweight: abstract enjoy meta class. The superclass or interface of all the specific classes of the class, through which flyweight can accept and act on external topics
concreteflyweight: The specific share of the meta-class. Specifies the internal state to increase storage space for the internal state.
flyweightfactory: Enjoy the Meta factory class. Used to create and manage flyweight objects, which are primarily used to ensure that flyweight is reasonably shared, and when a user requests a flyweight, Flyweightfactory provides a flyweight object that has already been created or creates a new one if it does not exist.
The core of the enjoy meta-factory class, the benefit of the meta-factory class is to provide a pool for the enjoyment of the meta-object, the user needs the object, first obtained from the pool of enjoyment, if the pool does not exist, a new object is created to return to the user, and in the pool to save the new objects.
Code:

AbstractClass Flywight {Abstract voidOperation (String externalstate);} Class Concreteflyweight extends Flywight {PrivateString internalstate; Public Concreteflyweight(String internalstate) { This. internalstate = internalstate; }@Override    voidOperation (String externalstate) {System.out.println ("Internal status:"+ internalstate); System.out.println ("External state:"+ externalstate); }}class flyweightfactory {hashmap<string, flywight> map =NewHashmap<> (); PublicFlywightGetflyweight(String State) {Flywight flywight = Map.get (state);if(Flywight = =NULL) {Flywight =NewConcreteflyweight (state);        Map.put (state, flywight); }returnFlywight; }}

(b) compound mode of enjoyment:
In the simple-to-enjoy meta-mode, all the objects of the object are simply to enjoy the meta-object, which means they can be shared directly. There is also a more complex situation, the use of a few simple-to-enjoy composite model to compound, to form a compound to enjoy meta-objects. Such compound-sharing objects cannot be shared by themselves, but they can be decomposed into simple-to-enjoy meta-objects, while the latter can be shared.

class Diagram:

role:
abstract Flyweight : An abstract interface is given to specify the methods that are required to be implemented by all the specific privilege meta roles.
specific Concreteflyweight: Implements the interface defined by the abstract privileges meta role. If there is an intrinsic state, you must be responsible for providing storage space for the intrinsic state.
Compound Concretecompositeflyweight : The objects represented by the compound-enjoy meta-role are not shareable, but a composite-object can be decomposed into multiple combinations of primitive objects. The compound privilege role is also known as a non-shareable, shared meta object.
enjoy meta factory (flyweightfactory) : Responsible for creating and managing the rewards role.

Code:

AbstractClass Flywight {Abstract voidOperation (String externalstate);} Class Concreteflyweight extends Flywight {PrivateString internalstate; Public Concreteflyweight(String internalstate) { This. internalstate = internalstate; }@Override    voidOperation (String externalstate) {System.out.println ("Internal status:"+ internalstate); System.out.println ("External state:"+ externalstate); }}class Concretecompositeflyweight extends Flywight {map<string, flywight> list =NewHashmap<> (); Public void Add(String state, Flywight Flywight)    {List.put (state, flywight); }@Override    voidOperation (String externalstate) { for(Map.entry<string, Flywight> data:list.entrySet ())        {Data.getvalue (). operation (Externalstate); }}}class flyweightfactory {hashmap<string, flywight> map =NewHashmap<> (); PublicFlywightGetflyweight(list<string> states) {Concretecompositeflyweight Ccflyweight =NewConcretecompositeflyweight (); for(String state:states) ccflyweight.add (state, Getflyweight (state));returnCcflyweight; } PublicFlywightGetflyweight(String State) {Flywight flywight = Map.get (state);if(Flywight = =NULL) {Flywight =NewConcreteflyweight (state);        Map.put (state, flywight); }returnFlywight; }}

Advantages and Disadvantages:
The advantage of the enjoy meta-mode is that it drastically reduces the number of objects in memory. However, the cost of doing this is also high:
1) Enjoy meta mode makes the system more complex. In order for objects to be shared, some States need to be externally instantiated, which complicates the logic of the program.
2) The enjoy meta-mode will allow the state of the meta-object to be instantiated, while reading the external state makes the run time slightly longer.

Design Pattern Summary: Structural model (bottom)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.