Decorative pattern design patterns

Foreword

Decorative patterns, refers 动态to add some additional responsibilities to an object, you add functionality, the decorative pattern is more flexible with respect to subclass it.

Scene introduced

A person, behavior is sleep eat and drink, and now we want to make this man to become Superman, that has functions to save the world.

Here Insert Picture Description
Abstract decorator AbstractDecoratorhas an abstract class AbstractPersonsubclass object, and can AbstractPersonsubclass object is modified.

So no modifications personunder the circumstances to achieve the specific class, modified into ConcreteSuperPersonDecoratorclass

1. abstract class
/**
 * @author 阳光大男孩!!!
 */
public abstract class AbstractPerson {
    /**
     * 动作
     */
    abstract void action();
}


2. Human implementation class
/**
 * @author 阳光大男孩!!!
 */
public class ConcretePerson extends AbstractPerson{

    @Override
    void action() {
        System.out.println("吃...睡...");
    }
}


3. decorative abstract class
/**
 * @author 阳光大男孩!!!
 */
abstract class AbstractDecorator extends AbstractPerson {
	/**
     * 被装饰的对象
     */
    protected AbstractPerson abstractPerson;
	
    public void setPerson(AbstractPerson abstractPerson) {
        this.abstractPerson = abstractPerson;
    }
    @Override
    void action() {
        if(abstractPerson!=null)
        {
            abstractPerson.action();//实际上执行的是abstractPerson的action()方法
        }
    }
}


This abstract class subclass can be other classes 装饰.

4. decorator abstract class implementation class
/**
 * @author 阳光大男孩!!!
 */
public class ConcreteSuperPersonDecorator extends  AbstractDecorator{
    @Override
    void action() {
        super.action();
        System.out.println("拯救世界...");
    }
}


5. Test
/**
 * @author 阳光大男孩!!!
 */
public class Main {
    public static void main(String[] args) {
        //普通人吃和睡
        ConcretePerson person = new ConcretePerson() ;
        person.action();

        System.out.println("在不改动普通人类的情况下,增加新的功能:");

        ConcreteSuperPersonDecorator csd = new ConcreteSuperPersonDecorator();
        csd.setPerson(person);
        csd.action();

    }
}

operation result

......
在不改动普通人相关类的情况下,增加新的功能:......
拯救世界...
to sum up

Decorators need only care about their functions, without the need to be concerned about how the new functions are added to the object in the chain.

Published 211 original articles · won praise 101 · views 40000 +

Guess you like

Origin blog.csdn.net/weixin_43889841/article/details/104113407
Recommended