Java装饰器模式

Java的装饰器模式是结构型模式的一种,目的是增强被装饰类的功能,在JDK中,IO就使用了装饰器模式。

下面是代码:

人的接口:

public interface Human {

    void run();
}

男人:

public class Man implements Human {

    @Override
    public void run() {
        System.out.println("人可以走");
    }

}

超人:

/**
 * 装饰类,可以把人进化为超人,然后增强run方法
 */
public class SuperMan implements Human {

    private Human human;


    SuperMan(Human human){
        this.human = human;
    }

    private void fly(){
        System.out.println("走的速度达到了就能飞了");
    }

    @Override
    public void run() {
        this.human.run();
        this.fly();
    }
}

测试代码:

public class DecoratorTest {

    public static void main(String[] args) {
        // 当人没有进化成超人的时候
        Human man = new Man();
        man.run();

        // 把人进化装饰成超人
        SuperMan superMan = new SuperMan(man);
        //进化成超人的人,就能速度达到就能飞
        superMan.run();
    }

}

测试结果:

人可以走
人可以走
走的速度达到了就能飞了

装饰器模式就是为了增强某一个类,并且是在原来的类的功能不变的情况下。这在框架中应用很广,如果我们要升级某一项功能,原来的类是能正常运行的,如果我们改原来的代码,原来的类被成千上万个类引用,哪改一发而动全身,这个代价是很大的,装饰器模式可以为我们解决增强一个类,但是又不修改原来的类的解决方案。

装饰器模式是一种结构型设计模式,它允许你通过将对象放入包含行为的特殊封装对象来为原对象绑定新的行为。在装饰器模式,这些封装对象称为装饰器。 在 Java 装饰器模式通常用于动态地修改对象的运行时行为,而不是在编译时就静态地修改代码。这种模式可以让你在不改变一个对象的前提下给其增加新的功能。 具体实现时,装饰器类和被装饰类通常都实现同一个接口或继承同一个父类,这样可以保证它们之间的互换性。 下面是一个简单的示例代码: ```java interface Component { void operation(); } class ConcreteComponent implements Component { public void operation() { System.out.println("ConcreteComponent.operation()"); } } class Decorator implements Component { private Component component; public Decorator(Component component) { this.component = component; } public void operation() { component.operation(); } } class ConcreteDecoratorA extends Decorator { public ConcreteDecoratorA(Component component) { super(component); } public void operation() { super.operation(); System.out.println("ConcreteDecoratorA.operation()"); } } class ConcreteDecoratorB extends Decorator { public ConcreteDecoratorB(Component component) { super(component); } public void operation() { super.operation(); System.out.println("ConcreteDecoratorB.operation()"); } } public class Main { public static void main(String[] args) { Component component = new ConcreteComponent(); component = new ConcreteDecoratorA(component); component = new ConcreteDecoratorB(component); component.operation(); } } ``` 输出结果为: ``` ConcreteComponent.operation() ConcreteDecoratorA.operation() ConcreteDecoratorB.operation() ``` 这个示例,`Component` 接口定义了一个 `operation()` 方法,`ConcreteComponent` 类实现了这个接口并提供了具体的实现。`Decorator` 类也实现了 `Component` 接口,并在其构造函数接收一个 `Component` 对象,它的 `operation()` 方法会调用被装饰对象的 `operation()` 方法。`ConcreteDecoratorA` 和 `ConcreteDecoratorB` 类都继承自 `Decorator` 类,并在其 `operation()` 方法先调用父类的 `operation()` 方法,再添加自己的行为。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值