设计模式之装饰器模式

2020-10-17  本文已影响0人  HeloWxl

一个简单的实例(轻颜相机) 了解适配器模式

补妆这个操作,我们用代码如何完成?装饰器模式帮你

1.抽象组件

/**
* @Description:  抽象组件
*/
public interface Character {
   /**
   * @Description: 补妆
   */
   String touchUp();
}

2.装饰器

/**
* @Description: 装饰器
 *              1.抽象类
 *              2.实现抽象组件接口
 *              3.持有抽象接口的引用
*/
public abstract class AbstractDecorate implements Character {

    /**
    * @Description: 定义私有的人物接口引用
    */
    private Character character;

    public AbstractDecorate(Character character){
        this.character = character;
    }

    /**
     * @Description: 补妆
     */
    @Override
    public String touchUp() {
        return this.character.touchUp();
    }
}

3.被装饰者

/**
 * @Description: 被装饰者 女生
 */
public class Girl implements Character{

    @Override
    public String touchUp() {
        return "我是个漂亮女生,我想发自拍,我要美颜 ";
    }
}

涂口红

/**
* @Description: 口红
*/
public class Lipstick extends AbstractDecorate{

    public Lipstick(Character character) {
        super(character);
    }

    @Override
    public String touchUp() {
        return super.touchUp()+"+涂口红";
    }
}

画眉毛

/**
 * @Description: 眉毛
 */
public class EyeBrow extends AbstractDecorate{

    public EyeBrow(Character character) {
        super(character);
    }

    @Override
    public String touchUp() {
        return super.touchUp()+"+画眉毛";
    }
}

涂眼影

/**
* @Description: 眼影
*/
public class EyeShadow extends AbstractDecorate{
    public EyeShadow(Character character) {
        super(character);
    }

    @Override
    public String touchUp() {
        return super.touchUp()+"+涂眼影";
    }
}

测试

public class Test {

    public static void main(String[] args) {
        Character girl = new Girl();
        System.out.println(girl.touchUp());

        //todo 涂口红
        Character lipStickGirl = new Lipstick(girl);
        System.out.println(lipStickGirl.touchUp());

        //todo 画眉毛
        Character eyeBrowGirl = new EyeBrow(lipStickGirl);
        System.out.println(eyeBrowGirl.touchUp());

        //todo 涂眼影
        Character eyeShadowGirl = new EyeShadow(eyeBrowGirl);
        System.out.println(eyeShadowGirl.touchUp());
    }
}

打印结果:

image.png

下一篇:工厂模式

上一篇下一篇

猜你喜欢

热点阅读