Java中装饰模式(Decorator)_JAVA_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > JAVA > Java中装饰模式(Decorator)

Java中装饰模式(Decorator)

 2018/10/22 12:18:32  andrew7676  程序员俱乐部  我要评论(0)
  • 摘要:1.Java中装饰模式(Decorator)publicinterfaceComponent{publicvoiddoSomething();}publicclassConcreteComponentimplementsComponent{@OverridepublicvoiddoSomething(){System.out.println("功能A");}}publicclassDecoratorimplementsComponent{privateComponentcomponent
  • 标签:ORA Java 模式 装饰模式
1. Java中装饰模式(Decorator)
class="Component.java" name="code">
public interface Component{
    public void doSomething();
}

public class ConcreteComponent implements Component{
    @Override
    public void doSomething(){
        System.out.println("功能A");
    }
}

public class Decorator implements Component{
    private Component component;
    public Decorator(Component component){
        this.component = component;
    }
    @Override
    public void doSomething(){
        component.doSomething();
    }
}

public class ConcreteDecorator1 extends Decorator{
    public ConcreteDecorator1(Component component){
        super(component);
    }
    @Override
    public void doSomething(){
        super.doSomething();
        this.doAnotherThing();
    }
    private void doAnotherThing(){
        System.out.println("功能B");
    }
}

public class ConcreteDecorator2 extends Decorator{
    public ConcreteDecorator2(Component component){
        super(component);
    }
    @Override
    public void doSomething(){
        super.doSomething();
        this.doAnotherThing();
    }
    private void doAnotherThing(){
        System.out.println("功能C");
    }
}

public class Client {
    public static void main(String[] args) {
        // 节点流
        Component component = new ConcreteComponent();
        // 过滤流
        Component component2 = new ConcreteDecorator1(component);
        component2.doSomething();
        System.out.println("------------");
        // 过滤流
        Component component3 = new ConcreteDecorator2(component2);
        component3.doSomething();
        System.out.println("------------");
        Component component11 = new ConcreteDecorator1(new ConcreteDecorator2(new ConcreteComponent()));
        component11.doSomething();
    }
}
上一篇: Java中I/O的字符流InputStreamReader和OutputStreamWriter 下一篇: 没有下一篇了!
发表评论
用户名: 匿名