返回顶部

结构型之【装饰器模式】

定义:

装饰器模式(Decorator Pattern) 也称为包装模式(Wrapper Pattern) 是指在不改变原有对象的基础之上,将功能附加到对象上,提供了比继承更有弹性的替代方案(扩展原有对象的功能),属于结构型模式。装饰器模式的核心是功能扩展,使用装饰器模式可以透明且动态地扩展类的功能

一、Person接口

public interface Person {
    void GetRole();
    void GetAge();
}

二、定义Father类并实现Person接口

复制代码
public class Father implements Person  {

    @Override
    public void GetRole() {
        System.out.println("role : father");
    }
    @Override
    public void GetAge() {
        System.out.println("father age : 38 years");
    }
}
复制代码

 

三、定义Mother类并实现Person接口

复制代码
public class Mother implements Person {

    @Override
    public void GetRole() {
        System.out.println("role : Mother");
    }

    @Override
    public void GetAge() {
        System.out.println("Mother Age : 30 years");
    }

}
复制代码

 

四、定义Son类并实现Person接口

复制代码
public class Son  implements Person{
    @Override
    public void GetRole() {
        System.out.println("son Age : 10 years");
    }

    @Override
    public void GetAge() {
        System.out.println("role : son");
    }
}
复制代码

 

五、定义PersonDecorator类并实现Person接口

复制代码
public class PersonDecorator implements Person{
    private  Person person;

    public PersonDecorator(Person person) {
        this.person = person;
    }

    @Override
    public void GetAge() {
        person.GetAge();
    }

    @Override
    public void GetRole() {
        person.GetRole();
    }
}
复制代码

六、定义PersonMaleDecorator类并继承PersonDecorator

复制代码
public class PersonMaleDecorator extends PersonDecorator {
    public PersonMaleDecorator(Person person) {
        super(person);
    }

    @Override
    public void GetAge() {
        super.GetAge();
        this.SetAddFunction();
    }

    @Override
    public void GetRole() {
        super.GetRole();
    }

    // 附加方法
    private  void  SetAddFunction()
    {
        System.out.println("this is a addfunction");
    }
}
复制代码

七、测试

复制代码
public class Main {
    public static void main(String[] args) {

        Mother mother=new Mother();
        PersonMaleDecorator father=new PersonMaleDecorator(new Father());
        PersonMaleDecorator son=new PersonMaleDecorator(new Son());

        mother.GetRole();
        mother.GetAge();
        System.out.println("------------------------");

        father.GetRole();
        father.GetAge();
        System.out.println("------------------------");

        son.GetRole();
        son.GetAge();
        System.out.println("------------------------");
    }
}
复制代码

 

posted @   SportSky  阅读(23)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?
作者:SportSky 出处: http://www.cnblogs.com/sportsky/ 本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。如果觉得还有帮助的话,可以点一下右下角的【推荐】,希望能够持续的为大家带来好的技术文章!想跟我一起进步么?那就【关注】我吧。
点击右上角即可分享
微信分享提示