设计模式-装饰模式
1.抽象构件角色:定义一个抽象接口,以规范准备接收附加责任的对象(interface Door)
package com.wh.decorate;
public interface Door
{
public void open();
}
2.具体构件角色:这是被装饰者,定义一个将要被装饰增加功能的类,有一个具体的方法,该类实现了抽象构件角色接口(class ConcreteDoor)
package com.wh.decorate;
public class ConcreteDoor implements Door
{
@Override
public void open()
{
System.out.println("门可打开!");
System.out.println("门可上锁!");
System.out.println("门可关闭!");
}
}
3.抽象装饰角色:该类实现了抽象构件角色的接口,持有一个具体构件对象的实例,实例方法构成接口抽象方法的方法体(class Decoration)
package com.wh.decorate;
public class Decoration implements Door
{
private Door door;
public Decoration(Door door)
{
this.door = door;
}
@Override
public void open()
{
door.open();
}
}
4.具体的装饰角色:负责给具体构件添加功能,重写继承自抽象装饰角色的方法,也可以添加自己的新功能(class RingDecoration class AlarmDecoration)
package com.wh.decorate;
public class RingDecoration extends Decoration
{
public RingDecoration(Door door)
{
super(door);
}
@Override
public void open()
{
super.open();
this.ring();
}
public void ring()
{
System.out.println("门有门铃!");
}
}
package com.wh.decorate;
public class AlarmDecoration extends Decoration
{
public AlarmDecoration(Door door)
{
super(door);
}
@Override
public void open()
{
super.open();
this.alarm();
}
public void alarm()
{
System.out.println("门有警报!");
}
}
5.具体的测试类(class Test)
package com.wh.decorate;
public class Test
{
public static void main(String[] args)
{
/*
* 具体的门 ->具体构件
*/
System.out.println("----具体的门---- ");
Door door = new ConcreteDoor();
door.open();
/*
* 装饰->添加门铃
*/
System.out.println("----添加门铃装饰----");
Door ring = new RingDecoration(door);
ring.open();
/*
* 装饰->添加警报
*/
System.out.println("----添加警报装饰----");
Door alarm = new AlarmDecoration(door);
alarm.open();
/*
* 在有门铃的门上加警报
*/
System.out.println("----添加门铃的门上加警报装饰----");
Door ringAndAlarm = new RingDecoration(alarm);
ringAndAlarm.open();
/*
* 在有警报的门上加门铃
*/
System.out.println("----在有警报的门上加门铃装饰----");
Door alarmAndRing = new AlarmDecoration(ring);
alarmAndRing.open();
/*
* 连续添加
*/
System.out.println("---连续添加装饰---");
Door decorations = new AlarmDecoration(new RingDecoration(new ConcreteDoor()));
decorations.open();
}
}