您的位置:首页 > 编程语言 > Java开发

Java装饰模式(Decorator)—结构型

2016-07-08 11:54 501 查看

意图

装饰模式以对客户透明的方式扩展对象的功能,是继承关系的一个替代方案。

类图与角色



抽象构件(Component):具体构件必须实现的接口。
具体构件(Concrete Component):对Component接口的实现。
装饰者接口(Decorator):持有一个构件(component)对象的实例,并定义一个与抽象构件接口一致的接口。
具体装饰者(Concrete Decorator):对Decorator接口的实现。

实例

//抽象构件
interface Engine{//引擎
public void work();
}
//具体构件
class GermanyEngine implements Engine{
public void work(){
System.out.println("引擎正常运转");
}
}
//装饰者接口
abstract class  MonitorEngine implements Engine{//具有监视功能的引擎
private Engine engine;
public MonitorEngine(Engine engine){
this.engine=engine;
}
@Override
public void work(){
engine.work();
}

}
//具体装饰者
class TemperatureMonitorEngine extends MonitorEngine{
public TemperatureMonitorEngine(Engine engine){
super(engine);
}
@Override
public void work(){
System.out.println("获取温度并发送给监控系统");
super.work();
}
}
class SpeedMonitorEngine extends MonitorEngine{
public SpeedMonitorEngine(Engine engine){
super(engine);
}
public void work(){
System.out.println("获引擎转速并发送给监控系统");
super.work();
}
}
class OilMonitorEngine extends MonitorEngine{
public OilMonitorEngine(Engine engine){
super(engine);
}
public void work(){
System.out.println("获引擎油量并发送给监控系统");
super.work();
}
}
//客户端代码
class test  {
public static void main (String[] args) throws java.lang.Exception{
Engine engine=new GermanyEngine();
engine=new TemperatureMonitorEngine(engine);
engine=new SpeedMonitorEngine(engine);
engine=new OilMonitorEngine(engine);
engine.work();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: