装饰模式

package 装饰模式;

public class DecoratorA implements MyInterface{
     MyInterface myObject;
    
    
    
    public DecoratorA(MyInterface myObject) {
        super();
        this.myObject = myObject;
    }



    @Override
    public void print() {
        System.out.print("hello!");
        myObject.print();
        System.out.println();
    }
}


package 装饰模式;

public class DecoratorB implements MyInterface{
    MyInterface myObject;
    
    
    public DecoratorB(MyInterface myObject) {
        super();
        this.myObject = myObject;
    }


    @Override
    public void print() {
        // TODO Auto-generated method stub
        System.out.print("my ");
        myObject.print();
    }

}
------------------------------------

package 装饰模式;

public interface MyInterface {

    void print();
}

--------------------------------

package 装饰模式;

public class Myclass implements MyInterface{

    /**装饰模式
     * 1)抽象构件角色(Component):定义一个抽象接口MyInterface,以规范准备接收附加责任的对象。

      2)具体构件角色(Concrete Component):这是被装饰者Myclass,定义一个将要被装饰增加功能的类。

      3)装饰角色(Decorator):持有一个构件对象的实例a,b,并定义了抽象构件定义的接口。

      4)具体装饰角色(Concrete Decorator):负责给构件添加增加的功能
     * @param args
     *
     */
    
    
    
    public static void main(String args[]){
        //输出my hello world
        MyInterface a = new DecoratorB(new DecoratorA(new Myclass()));
          a.print();
          //输出hello world
          a=new DecoratorA(new Myclass());
          a.print();
         //输出my world
          MyInterface b=new DecoratorB(new Myclass());
          b.print();
    }
     public void print(){
         System.out.print("world ");
     };
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值