装饰模式(Decorator)

mac2026-05-23  3

顾名思义,装饰模式就是给一个对象增加一些新的功能,而且是动态的,要求装饰对象和被装饰对象实现同一个接口,装饰对象持有被装饰对象的实例。

多线程类Thread是就是具体的应用体现

public interface Sourceable { public void method(); } //---------------------------------------------------- public class Source implements Sourceable { @Override public void method() { System.out.println("the original method!"); } } //---------------------------------------------------- public class Decorator implements Sourceable { private Sourceable source; public Decorator(Sourceable source) { super(); this.source = source; } @Override public void method() { System.out.println("beforedecorator!"); source.method(); System.out.println("afterdecorator!"); } } //---------------------------------------------------- public class DecoratorTest { public static void main(String[] args) { Sourceable source = new Source(); Sourceable obj = new Decorator(source); obj.method(); } }

多线程类Thread是就是具体的应用体现

Threa()实现了Runable()接口。在实例化Thread类的时候,可以传入一个实现了Runable接口的类的对象

最新回复(0)