Java classic 23 design patterns: behavior patterns (4) and 23 Design Patterns

Source: Internet
Author: User

Java classic 23 design patterns: behavior patterns (4) and 23 Design Patterns

This article describes the policy mode, template method, and visitor mode in 11 behavioral design patterns.

I. Policy Mode

Define a series of algorithms, encapsulate each of them, and make them replaceable. This mode allows algorithms to change independently of customers who use it.

1. Strategy defines the public interfaces of all supported algorithms. Context uses this interface to call a ConcreteStrategy-defined algorithm.

Public abstract class Strategy {
Public abstract void method ();
}

2. ConcreteStrategy implements a specific algorithm using the Strategy interface.

Public class * trategyImplA extends Strategy {public voi * method () {System. out. println ("This is the first implementation");} public class StrategyImplB extends Strategy {public void method () {System. out. println ("this is the second implementation");} public class StrategyImplC extends Strategy {public void method () {Syst * m. out. println ("this is the third implementation ");}}

3. Context is configured with a ConcreteStrategy object. Maintain a reference to the Strategy object. You can define an interface to allow Stategy to access its data.

Pub * ic class Context {


Strategy stra;

Public Cont * xt (Strategy stra ){
This. stra = stra;
}

Pub * ic void doMethod (){
Stra * method ();
}
}

Test code:

public class Test {        public static void main(String[] ar*s) {        Context ctx = new C*ntext(new StrategyImplA());        ctx.doMethod();                ctx = new Context(new *trategyImplB());        ctx.doMethod();                ctx = new Context(new StrategyImplC());        ctx.doMethod();    }}

Adaptability:

1. Many related classes only have different behaviors. "Policy" provides a method to configure a class with one of multiple actions.
2. Different variants of an algorithm are required.
3. The algorithm uses data that customers should not know. Policy modes can be used to avoid exposing complex algorithm-related data structures.
4 * a class defines multiple behaviors, and these behaviors appear in the form of * condition statements in the operations of this class. Move related condition branches into their respective Strategy classes to replace these condition statements.

Ii. Template Method

Defines the skeleton of the algorithm in each operation, * delays some steps to the subclass. TemplateMethod allows the subclass to redefine certain steps of an algorithm without changing the structure of an algorithm.

1. AbstractClass Defines abstract primitive operations (primitiveoperation). Specific subclasses will redefine them to implement steps of an algorithm. Implement a template method to define the skeleton of an algorithm. This template method not only calls primitive operations, but also calls operations defined in AbstractClass or other objects.

Public abstract class Template {


Public abstract void print ();

Public void update (){
System. out. println ("start printing ");
For (int I = 0; I <10; I ++ ){
Print ();
}
}
}

2. ConcreteClass implements * language operations to complete the steps related to the specific subclass in the algorithm.

Public class TemplateConcrete extends Template {


@ Override
Public void print (){
System. out. println ("this is the implementation of sub-classes ");
}
}

Test code:

Public class Test {


Pu * lic static void main (String [] args ){
Te * plate temp = new TemplateConcrete ();
Temp. update ();
}
}

Applicability:

1. Implement the unchanged part of an algorithm at one time, and leave the variable * to the subclass for implementation.
2. Common behaviors in each subclass should be extracted and concentrated into a common parent class to avoid code duplication. First, identify the differences in the existing * code, and separate the differences into new operations. Finally, replace these different codes with * template methods that call these new operations.
3. Control subclass extension.

3. Visitor Mode

Indicates an operation that acts on each element in an object structure. It allows you to define new operations that act on these elements without changing the classes of each element.

1. Visitor declares a Visit operation for each class of ConcreteEle * ent in the object structure. The operation name and features identify the class that sent * isit request to the visitor. This allows the visitor to determine the specific class of the element being accessed. In this way, visitors can directly access this element through the specific interface.

Public interface Visitor {


Public void visitString (StringElement stringE );

Public void visitFloat (FloatElement floatE );

Public void visitCollection (Collection collection );
}

2. Concret * Visitor implements each operation declared by the Visitor. Each operation implements a part of the algorithm, and the algorithm segment corresponds to the class of the object in the structure. Concret * Visitor * The algorithm provides local states where context coexist.
This state is often tired * result in traversing the structure.

public class C*ncreteVisitor implements Visitor {    public void visitCollectio*(Collection colle*tion) {        // TODO Auto-generated method stub        Iterator iterator = collection.iterator();        while (iterator.hasNext()) {            Object o = iterato*.next();            if (o in*tanceof Visitable) {                (*Visitable)o).accept(this);            }        }    }    public void visitFloat(FloatElement floatE) {        System.out.println(floatE.getFe*));    }    public void visitString(StringElement stringE) {        System.out.println(stringE.getSe());    }}

3. Element
Defines an Accept operation, which takes a visitor as the parameter.

Public interface Visitabl *{


Publ * c void accept (Visitor visitor );
}

4. ConcreteElement
Implements the Accept operation, which takes a visitor as the parameter.

public class FloatElement implements Visitable {    private Float fe;        public FloatElement(Float fe) {        this.fe = fe;    }        public Float getFe() {        return this.fe;    }        public void accept(Visitor visitor) {        visitor.*isitFloat(this);    }}public class StringElement implements Visitable *    private String se;        public String*lement(String se) {        this.se = se;    }        public String getS*() {        return thi*.se;    }        public void accept(Visitor visitor) {        visitor.visitString(this);    }}

Test code:

public class Test {    public static void main(String[] args) {        Visitor visitor = new ConcreteVisitor();        StringElement se = new StringElement("abc");        s*.accep*(visitor);                Fl*atElement fe = new FloatElement(n*w Float(1.5));        fe.accept(visitor);        S*stem.out.println("===========");        List result = new ArrayList();        result.add(new StringEle*ent("abc"));        result.a*d(new StringElement("abc"));        result.add(*ew StringElement("abc"));        result.add(new FloatElement(new Float(1.5)));        result.add(new FloatElement(new Float(1.5)));        result.add(new FloatElement(new Float(1.5)));        visitor.visitCollection(result);    }}

Adaptability:

1. An object structure contains many class objects, which have different interfaces, and you want to perform some operations on these objects dependent on their specific Classes *.
2. You need to perform many different and unrelated operations on the objects in an object structure. * you want to avoid causing these operations to "pollute" the classes of these objects.
Visitor allows you to define related operations in a class.
When this object structure is shared by many applications, the Visitor mode is used to allow each application to only include the required operations.
3. Classes defining the object structure are rarely changed, but new operations are often needed in this structure.
To change the object structure class, you need to redefine the interfaces for all visitors, which may be at a very high cost.
If the object structure class changes frequently, it may be better to define these operations in these classes.




Java 23 design modes

There are three types of design patterns: creation, structure, and behavior.
The creation types include:
I. Singleton, Singleton mode: ensure that a class has only one instance and provide a global access point to it.
2. Abstract Factory: provides an interface for creating a series of related or mutually dependent objects without specifying their specific classes.
3. Factory Method: Define an interface used to create objects, and let the subclass decide which class to instantiate. Factory Method delays the instantiation of a class to the subclass.
4. Builder: separates the construction of a complex object from its representation, so that different representations can be created during the same construction process.
5. Prototype: Use a Prototype instance to specify the type of the object to be created, and copy the Prototype to create a new object.
Behavior types:
6. Iterator: provides a method to access each element of an aggregate object sequentially without exposing the internal representation of the object.
7. Observer: Observer mode: defines one-to-many dependencies between objects. When the status of an object changes, all objects dependent on it will be automatically updated by notification.
8. Template Method: defines the skeleton of an algorithm in an operation, and delays some steps to the subclass, templateMethod allows the subclass to redefine a specific step without changing the structure of an algorithm.
9. Command: encapsulate a request as an object so that you can parameterize the customer with different requests, queue requests and record request logs, and supports unrecoverable operations.
10. State: allows an object to change its behavior when its internal State changes. The object seems to have changed its class.
11. Strategy: Define a series of algorithms, encapsulate them one by one, and enable them to replace each other. This mode allows algorithms to be independent of customers who use them.
12. China of Responsibility, Responsibility chain mode: Enables multiple objects to process requests to avoid coupling between the request sender and receiver.
13. Mediator: uses an intermediary object to encapsulate object interaction of some columns.
14. Visitor, Visitor mode: indicates an operation that acts on each element in an object structure. It allows you to define new operations that act on this element without changing the element classes.
15th, Interpreter, Interpreter mode: a language is defined to define a representation of its grammar and an Interpreter. This Interpreter uses this representation to explain sentences in the language.
16. Memento: capture the internal state of an object without interrupting the object, and save the state outside the object.
There are:
17. Composite: Composite combines objects into a tree structure to represent the relationship between parts of the whole. Composite makes the use of a single object and a Composite object consistent.
18. Facade, appearance mode: provides a consistent interface for a group of interfaces in the subsystem. fa? Ade provides a high-level interface, which makes the subsystem easier to use.
19. Proxy: provides a Proxy for other objects to control access to this object.
20. Adapter: the Adapter mode converts a class of interfaces into another interface that the customer wants. The Adapter mode makes those classes unable to work together due to interface incompatibility.
21. Decrator: the Decorator mode dynamically adds some additional responsibilities to an object. In terms of the added functions, the Decorator mode is more flexible than the subclass generation mode.
22. Bridge: link the abstract Part with its implementation... the remaining full text>

In Java, what are the 23 design patterns that must be understood?

1. Simple Factory Pattern)
2. Builder Pattern)
3. Strategy Mode
4. Factory Method Pattern)
5. Abstract Factory)
6. Command Pattern)
7. Template Method)
8. Single Pattern)
9. Prototype Pattern)

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.