5.4 设计模式
- 软件设计的总结,是一种参考答案,是重用经验
- 建筑模式 -> 设计模式(GoF)
5.4.3 Builder模式
- 创建型设计模式,使用多个步骤,分步地创建一个对象
- 举例:StringBuilder,Append、Insert、Remove、Replace都有多种重载形式,最终利用toString()得到字符串
- 应用:装配电脑
5.4.4 Factory模式
- 专门负责创建对象,工厂模式、抽象工厂
- 应用:断开两个类的直接依赖关系
- 实现:工厂类包含一个返回接口/抽象类的静态方法,接受字符串或者初始化值等可区分的变量
Class Factory{
public static IXXX Create(String XXX){
switch(...){...}
}
}
- 实现:抽象工厂类只需要定义一个方法就行,对于具有复杂分类关系的类创建比较适用(需要额外分层)
- 应用2:在程序运行的时候,依据特定的情况临时决定创建哪种类型的对象
- 应用3:ASP.NET MVC中,请求处理管线
5.4.5 Decorator模式
- 不修改原始代码,动态给对象添加新的功能,满足开闭原则
- 实现:对象注入,扩充被注入对象的功能(即为什么要调用基类方法,首先基类不是接口,里面有东西,其次说明这里可以获取返回值,对基类功能进行扩充)
- 应用:InpusStream及其子类
5.4.5 Composite模式
- 需要有意地忽略整体和部分的不同,只关注它们的共性,并且基于这种共性完成某种工作
- 应用:统计一个文件夹的容量:文件夹和文件是整体与部分的关系,它们都有一个占用磁盘空间的特性,我们忽略了他们的整体与部分的关系,只关注他们占用空间这个属性;适合树形结构
- 应用:电脑 = 机箱 + 主板 + 内存 + 硬盘,通过调用电脑的price方法,计算整台电脑的价格
abstract class Component{
String name;
int price;
component(String name, int price){
this.name = name;
this.price = price;
}
void add();
int getPrice();
}
abstract class CompositeComponent extends Component{ //继承的意思是可以把CompositeComponent也添加到components中
List<Component> components = new List<Component>;
compositeComponent(String name, int price){
super.compent(name, price) // 重用代码,第一行
}
public int getPrice(){ //调用compoture的getPrice实际上是调用这个,有一点点递归的意思
// return sum of prices in components and CompositeComponent itself
}
public void add(Component component){
// add component into components
}
}
class Computer extends CompositeComponent{
computer(){
super.compositeComponent('computer', )
}
}
- 应用:word中的组合图形
- 应用:ThreadGroup
5.4.7 Command模式
- 遥控器-命令-电视机
- 实现:Commend抽象类,ConcreteComment包含一个receiver属性和excute方法
interface ICommend{
void excute();
}
...
private void processReceivedCommand(Command command){
command.excute();
}
5.4.8 先学后创、先简后繁