Java classic 23 design patterns: behavioral patterns (4)

Source: Internet
Author: User

Java classic 23 design patterns: behavioral patterns (4)

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.



Related Article

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.