Head First设计模式:(三)装饰者模式

本文深入探讨装饰者模式在星巴兹咖啡订单系统中的应用,并通过Java I/O装饰者实例展示其扩展性和灵活性。

转:http://blog.youkuaiyun.com/lissdy/article/details/7540090


星巴兹咖啡准备更新订单系统,以合乎他们的饮料供应需求。

他们原先的类设计为:

这样的订单系统没有办法考虑到咖啡调料的部分,把加入不同调料的咖啡看做不同的类会导致类爆炸(每个类的cost方法计算出咖啡加调料的价钱):

很明显,这样的系统难以维护,一旦牛奶的价钱上扬或新增一种焦糖调料,系统将难以改变。

采用实例变量和继承的设计也许能解决一些问题:

Beverage作为一个饮料类,加上实例变量代表是否加入了饮料。

然而当用户想要双倍摩卡咖啡时,这样的系统就显得有些无所适从。

对于冰茶,饮料基类里的有些调料根本不适用,但是也一起继承了过来!

到目前为止,使用继承会造成的问题有:类爆炸,设计死板,以及基类加入的新功能并不适用于所有的子类。

所以继承并不是解决问题的方法,应当使用组合来使系统更有弹性且易于维护。

开放-关闭原则:

设计原则:

类应该对扩展开放,对修改关闭。

我们的目标是允许类容易扩展,在不修改现有代码的情况下,就可搭配新的行为。

这个目标需要使用装饰着模式实现:以饮料为主体,然后运行调料来“装饰”饮料。

如图为一个摩卡和奶泡DarkRoast咖啡的设计图:

定义装饰者模式:

装饰者模式动态的将责任附加到对象上,若要扩展功能,装饰者提供了比继承更具有弹性的替代方案。

装饰者模式类图:

现在让星巴兹咖啡系统也符合装饰者类图:

具体实现:

从饮料下手,将饮料作为一个抽象类:

[java]  view plain  copy
  1. package com.cafe;  
  2.   
  3. public abstract class Beverage {  
  4.     String description = "Unknow Beverage";  
  5.   
  6.     public String getDescription() {  
  7.         return description;  
  8.     }  
  9.   
  10.     public abstract double cost();  
  11. }  

调料抽象类,也就是装饰者类:

[java]  view plain  copy
  1. package com.cafe;  
  2.   
  3. public abstract class CondimentDecorator extends Beverage{  
  4.    public abstract String getDescription();  
  5. }  

实现具体的饮料(浓缩咖啡和综合咖啡):

[java]  view plain  copy
  1. package com.cafe;  
  2.   
  3. public class Espresso extends Beverage {  
  4.     public Espresso() {  
  5.         description = "Espresso";  
  6.     }  
  7.   
  8.     public double cost() {  
  9.         return 1.99;  
  10.     }  
  11. }  
[java]  view plain  copy
  1. package com.cafe;  
  2.   
  3. public class HouseBlend extends Beverage {  
  4.     public HouseBlend() {  
  5.         description = "HouseBlend";  
  6.     }  
  7.   
  8.     public double cost() {  
  9.         return 0.89;  
  10.     }  
  11. }  

实现具体装饰者类(摩卡)

[java]  view plain  copy
  1. package com.cafe;  
  2.   
  3. public class Mocha extends CondimentDecorator{  
  4.     Beverage beverage;  
  5.     public Mocha(Beverage beverage)  
  6.     {  
  7.         this.beverage=beverage;  
  8.     }  
  9.     public String getDescription()  
  10.     {  
  11.         return beverage.getDescription()+", Mocha";  
  12.     }  
  13.     public double cost()  
  14.     {  
  15.         return 0.20+beverage.cost();  
  16.     }  
  17. }  

其他装饰者类的实现方式与摩卡类似。

测试代码:

[java]  view plain  copy
  1. package com.cafe;  
  2.   
  3. public class StartbuzzCoffee {  
  4.     public static void main(String args[]) {  
  5.         Beverage beverage1 = new Espresso();  
  6.         System.out.println(beverage1.getDescription() + "  $"  
  7.                 + beverage1.cost());  
  8.   
  9.         Beverage beverage2 = new HouseBlend();  
  10.         beverage2 = new Soy(beverage2);  
  11.         beverage2 = new Mocha(beverage2);  
  12.         beverage2 = new Whip(beverage2);  
  13.         System.out.println(beverage2.getDescription() + "  $"  
  14.                 + beverage2.cost());  
  15.     }  
  16.   
  17. }  

测试结果:


 Java中的装饰者模式(java.io类):

Java I/O引出装饰者模式的一个“缺点”:利用装饰者模式,会造成设计中存在大量的小类。

编写自己的java I/O装饰者,把输入流中的所有大写字母转成小写:

[java]  view plain  copy
  1. package com.io;  
  2.   
  3. import java.io.*;  
  4.   
  5. public class InputTest {  
  6.     public static void main(String[] args) throws IOException {  
  7.         int c;  
  8.   
  9.         try {  
  10.             InputStream in = new LowerCaseInputStream(new BufferedInputStream(  
  11.                     new FileInputStream("D:\\test.txt")));  
  12.   
  13.             while ((c = in.read()) >= 0) {  
  14.                 System.out.print((char) c);  
  15.             }  
  16.   
  17.             in.close();  
  18.         } catch (IOException e) {  
  19.             e.printStackTrace();  
  20.         }  
  21.     }  
  22. }  

测试程序(测试刚刚写好的I/O装饰者)

[java]  view plain  copy
  1. package com.io;  
  2.   
  3. import java.io.FilterInputStream;  
  4. import java.io.IOException;  
  5. import java.io.InputStream;  
  6.   
  7. public class LowerCaseInputStream extends FilterInputStream {  
  8.   
  9.     protected LowerCaseInputStream(InputStream in) {  
  10.         super(in);  
  11.         // TODO Auto-generated constructor stub  
  12.     }  
  13.   
  14.     public int read() throws IOException {  
  15.         int c = super.read();  
  16.         return (c == -1 ? c : Character.toLowerCase((char) c));  
  17.     }  
  18.   
  19.     public int read(byte[] b, int offset, int len) throws IOException {  
  20.         int result = super.read(b, offset, len);  
  21.         for (int i = offset; i < offset + result; i++) {  
  22.             b[i] = (byte) Character.toLowerCase((char) b[i]);  
  23.         }  
  24.         return result;  
  25.     }  
  26. }  

测试结果:




转:http://blog.youkuaiyun.com/jason0539/article/details/22713711

另外一个好例子


//定义被装饰者  
public interface Human {  
    public void wearClothes();  
  
    public void walkToWhere();  
}  
  
//定义装饰者  
public abstract class Decorator implements Human {  
    private Human human;  
  
    public Decorator(Human human) {  
        this.human = human;  
    }  
  
    public void wearClothes() {  
        human.wearClothes();  
    }  
  
    public void walkToWhere() {  
        human.walkToWhere();  
    }  
}  
  
//下面定义三种装饰,这是第一个,第二个第三个功能依次细化,即装饰者的功能越来越多  
public class Decorator_zero extends Decorator {  
  
    public Decorator_zero(Human human) {  
        super(human);  
    }  
  
    public void goHome() {  
        System.out.println("进房子。。");  
    }  
  
    public void findMap() {  
        System.out.println("书房找找Map。。");  
    }  
  
    @Override  
    public void wearClothes() {  
        // TODO Auto-generated method stub  
        super.wearClothes();  
        goHome();  
    }  
  
    @Override  
    public void walkToWhere() {  
        // TODO Auto-generated method stub  
        super.walkToWhere();  
        findMap();  
    }  
}  
  
public class Decorator_first extends Decorator {  
  
    public Decorator_first(Human human) {  
        super(human);  
    }  
  
    public void goClothespress() {  
        System.out.println("去衣柜找找看。。");  
    }  
  
    public void findPlaceOnMap() {  
        System.out.println("在Map上找找。。");  
    }  
  
    @Override  
    public void wearClothes() {  
        // TODO Auto-generated method stub  
        super.wearClothes();  
        goClothespress();  
    }  
  
    @Override  
    public void walkToWhere() {  
        // TODO Auto-generated method stub  
        super.walkToWhere();  
        findPlaceOnMap();  
    }  
}  
  
public class Decorator_two extends Decorator {  
  
    public Decorator_two(Human human) {  
        super(human);  
    }  
  
    public void findClothes() {  
        System.out.println("找到一件D&G。。");  
    }  
  
    public void findTheTarget() {  
        System.out.println("在Map上找到神秘花园和城堡。。");  
    }  
  
    @Override  
    public void wearClothes() {  
        // TODO Auto-generated method stub  
        super.wearClothes();  
        findClothes();  
    }  
  
    @Override  
    public void walkToWhere() {  
        // TODO Auto-generated method stub  
        super.walkToWhere();  
        findTheTarget();  
    }  
}  
  
//定义被装饰者,被装饰者初始状态有些自己的装饰  
public class Person implements Human {  
  
    @Override  
    public void wearClothes() {  
        // TODO Auto-generated method stub  
        System.out.println("穿什么呢。。");  
    }  
  
    @Override  
    public void walkToWhere() {  
        // TODO Auto-generated method stub  
        System.out.println("去哪里呢。。");  
    }  
}  
//测试类,看一下你就会发现,跟java的I/O操作有多么相似  
public class Test {  
    public static void main(String[] args) {  
        Human person = new Person();  
        Decorator decorator = new Decorator_two(new Decorator_first(  
                new Decorator_zero(person)));  
        decorator.wearClothes();  
        decorator.walkToWhere();  
    }  
}  //定义被装饰者  
public interface Human {  
    public void wearClothes();  
  
    public void walkToWhere();  
}  
  
//定义装饰者  
public abstract class Decorator implements Human {  
    private Human human;  
  
    public Decorator(Human human) {  
        this.human = human;  
    }  
  
    public void wearClothes() {  
        human.wearClothes();  
    }  
  
    public void walkToWhere() {  
        human.walkToWhere();  
    }  
}  
  
//下面定义三种装饰,这是第一个,第二个第三个功能依次细化,即装饰者的功能越来越多  
public class Decorator_zero extends Decorator {  
  
    public Decorator_zero(Human human) {  
        super(human);  
    }  
  
    public void goHome() {  
        System.out.println("进房子。。");  
    }  
  
    public void findMap() {  
        System.out.println("书房找找Map。。");  
    }  
  
    @Override  
    public void wearClothes() {  
        // TODO Auto-generated method stub  
        super.wearClothes();  
        goHome();  
    }  
  
    @Override  
    public void walkToWhere() {  
        // TODO Auto-generated method stub  
        super.walkToWhere();  
        findMap();  
    }  
}  
  
public class Decorator_first extends Decorator {  
  
    public Decorator_first(Human human) {  
        super(human);  
    }  
  
    public void goClothespress() {  
        System.out.println("去衣柜找找看。。");  
    }  
  
    public void findPlaceOnMap() {  
        System.out.println("在Map上找找。。");  
    }  
  
    @Override  
    public void wearClothes() {  
        // TODO Auto-generated method stub  
        super.wearClothes();  
        goClothespress();  
    }  
  
    @Override  
    public void walkToWhere() {  
        // TODO Auto-generated method stub  
        super.walkToWhere();  
        findPlaceOnMap();  
    }  
}  
  
public class Decorator_two extends Decorator {  
  
    public Decorator_two(Human human) {  
        super(human);  
    }  
  
    public void findClothes() {  
        System.out.println("找到一件D&G。。");  
    }  
  
    public void findTheTarget() {  
        System.out.println("在Map上找到神秘花园和城堡。。");  
    }  
  
    @Override  
    public void wearClothes() {  
        // TODO Auto-generated method stub  
        super.wearClothes();  
        findClothes();  
    }  
  
    @Override  
    public void walkToWhere() {  
        // TODO Auto-generated method stub  
        super.walkToWhere();  
        findTheTarget();  
    }  
}  
  
//定义被装饰者,被装饰者初始状态有些自己的装饰  
public class Person implements Human {  
  
    @Override  
    public void wearClothes() {  
        // TODO Auto-generated method stub  
        System.out.println("穿什么呢。。");  
    }  
  
    @Override  
    public void walkToWhere() {  
        // TODO Auto-generated method stub  
        System.out.println("去哪里呢。。");  
    }  
}  
//测试类,看一下你就会发现,跟java的I/O操作有多么相似  
public class Test {  
    public static void main(String[] args) {  
        Human person = new Person();  
        Decorator decorator = new Decorator_two(new Decorator_first(  
                new Decorator_zero(person)));  
        decorator.wearClothes();  
        decorator.walkToWhere();  
    }  
}  

运行结果:

其实就是进房子找衣服,然后找地图这样一个过程,通过装饰者的三层装饰,把细节变得丰富。

关键点:
1、Decorator抽象类中,持有Human接口,方法全部委托给该接口调用,目的是交给该接口的实现类即子类进行调用。
2、Decorator抽象类的子类(具体装饰者),里面都有一个构造方法调用super(human),这一句就体现了抽象类依赖于子类实现即抽象依赖于实现的原则。因为构造里面参数都是Human接口,只要是该Human的实现类都可以传递进去,即表现出Decorator dt = new Decorator_second(new Decorator_first(new Decorator_zero(human)));这种结构的样子。所以当调用dt.wearClothes();dt.walkToWhere()的时候,又因为每个具体装饰者类中,都先调用super.wearClothes和super.walkToWhere()方法,而该super已经由构造传递并指向了具体的某一个装饰者类(这个可以根据需要调换顺序),那么调用的即为装饰类的方法,然后才调用自身的装饰方法,即表现出一种装饰、链式的类似于过滤的行为。
3、具体被装饰者类,可以定义初始的状态或者初始的自己的装饰,后面的装饰行为都在此基础上一步一步进行点缀、装饰。
4、装饰者模式的设计原则为:对扩展开放、对修改关闭,这句话体现在我如果想扩展被装饰者类的行为,无须修改装饰者抽象类,只需继承装饰者抽象类,实现额外的一些装饰或者叫行为即可对被装饰者进行包装。所以:扩展体现在继承、修改体现在子类中,而不是具体的抽象类,这充分体现了依赖倒置原则,这是自己理解的装饰者模式。




基于径向基函数神经网络RBFNN的自适应滑模控制学习(Matlab代码实现)内容概要:本文介绍了基于径向基函数神经网络(RBFNN)的自适应滑模控制方法,并提供了相应的Matlab代码实现。该方法结合了RBF神经网络的非线性逼近能力和滑模控制的强鲁棒性,用于解决复杂系统的控制问题,尤其适用于存在不确定性和外部干扰的动态系统。文中详细阐述了控制算法的设计思路、RBFNN的结构与权重更新机制、滑模面的构建以及自适应律的推导过程,并通过Matlab仿真验证了所提方法的有效性和稳定性。此外,文档还列举了大量相关的科研方向和技术应用,涵盖智能优化算法、机器学习、电力系统、路径规划等多个领域,展示了该技术的广泛应用前景。; 适合人群:具备一定自动控制理论基础和Matlab编程能力的研究生、科研人员及工程技术人员,特别是从事智能控制、非线性系统控制及相关领域的研究人员; 使用场景及目标:①学习和掌握RBF神经网络与滑模控制相结合的自适应控制策略设计方法;②应用于电机控制、机器人轨迹跟踪、电力电子系统等存在模型不确定性或外界扰动的实际控制系统中,提升控制精度与鲁棒性; 阅读建议:建议读者结合提供的Matlab代码进行仿真实践,深入理解算法实现细节,同时可参考文中提及的相关技术方向拓展研究思路,注重理论分析与仿真验证相结合。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值