Java的装饰模式

1.装饰器模式又名包装(Wrapper)模式。装饰器模式以对客户端透明的方式拓展对象的功能,是继承关系的一种替代方案。

2.结构图

3.再来看一个简单的例子

3.1定义一个component接口

public interface People {
    void method();
}

3.2定义一个具体的实现接口类

public class XiaoMing implements People {
    @Override
    public void method() {
        System.out.println("小明打扮自己");
    }
}

3.3Decorator抽象类也实现接口,并且持有一个接口对象

public abstract class Decorator implements People {
    private People component;

    public Decorator(People component) {
        this.component = component;
    }

    @Override
    public void method() {
        component.method();
    }
}

3.4具体的装饰类,继承自decorator类,并且实现自己具体的装饰功能

public class DecoratorA extends Decorator {

    public DecoratorA(People component) {
        super(component);
    }

    @Override
    public void method() {
        super.method();
        System.out.println("摸化妆品");
    }
}
public class DecoratorB extends Decorator {

    public DecoratorB(People component) {
        super(component);
    }

    @Override
    public void method() {
        super.method();
        System.out.println("戴首饰");
    }
}

3.5测试类

public class Test {
    public static void main(String[] args) {
        //首先把实现类new出来
        People component = new XiaoMing();

        //把具体装饰者new出来
        People component1 = new DecoratorA(component);
        People component2 = new DecoratorB(component1);
        component2.method();
    }
}

打印结果:

4.总结:装饰模式主要是为了增加功能却不改变原有的功能而设计的,符合开闭原则;如上面的例子,在小明打扮自己时,可以首先调用打扮功能,接下来调用化妆品,再调用首饰;如果我们想再添加穿裙子功能,可以再写一个类,继承自抽象的decorator即可;原来的代码逻辑都不用动;调用时再多一步就好了;当功能多的时候;我们可以随意组合功能,得到我们想要的;

装饰模式是一种结构型设计模式,它允许在不修改原始类代码的情况下,通过使用继承和组合的方式,动态地为对象添加新的功能。在Java中,装饰模式通常使用抽象类和接口来实现。 以下是一个简单的Java装饰模式类图: ``` +---------------------+ | Component | +---------------------+ | | + Interface: Component | +-------------+ ------> ConcreteComponent | +-------------------+ | | + Interface: Component | +--+ | | + Abstract Class: Decorator | +------------+ | v +--------+ | ConcreteDecoratorA | +--------+ | | + Interface: Component | +-------------+ | | + Abstract Class: Decorator | +------------+ | v +---------------------+ | ConcreteDecoratorB | +---------------------+ ``` 在这个类图中,`Component`是一个接口,它定义了所有组件都应该具有的共同方法。`ConcreteComponent`是一个具体的组件类,实现了`Component`接口。`Decorator`是一个抽象类,它也实现了`Component`接口,并持有一个`Component`类型的引用。`ConcreteDecoratorA`和`ConcreteDecoratorB`是具体的装饰者类,它们分别继承了`Decorator`抽象类,并实现了各自的具体功能。 当需要给某个组件添加新功能时,可以使用装饰者模式。首先创建一个具体的组件类(如`ConcreteComponent`),然后创建一个抽象的装饰者类(如`Decorator`),并在抽象装饰者类中实现所需的功能。接着创建具体的装饰者类(如`ConcreteDecoratorA`和`ConcreteDecoratorB`),它们分别继承自抽象装饰者类,并实现各自的具体功能。最后,将具体组件类和具体装饰者类进行组合,即可得到具有新功能的对象。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值