【软件构造】5.3 面向复用的设计模式

面向复用的设计模式

结构型模式

1.Adapter 适配器模式

将某个类/接口转换为client期望的其他形式
增加一个接口,将已存在的子类封装起来,client面向接口编程,隐藏具体子类
在这里插入图片描述
示例:

interface Shape{
	void display(int x1,int y1,int x2,int y2);
}

class Rectangle implements Shape{
	void display(int x1,int y1,int x2,int y2) {
		new LegacyRectangle().display(x1, y1, x2-x1, y2-y1);
	}
}
class LegacyRectangle{
	void display(int x1,int y1,int w,int h) {
		...
	}
}
class Client{
	Shape shape = new Rectangle();
	public void display() {
		shape.display(x1, y1, x2, y2);
	}
}

在这里插入图片描述

2.Decorator 装饰器模式

为对象增加不同侧面的特性→通过创建一个包装对象,持有一个真实对象的引用,进而来装饰包裹真实的对象
通过一种无需定义子类的方法来给对象动态增加职责,使用对象之间的关联关系取代类之间的继承关系。在装饰模式中引入了装饰类,在装饰类中既可以调用被装饰的原有类的方法,还可以增加新的方法,以扩充原有类的功能。
示例:

class Decorator implements Component {
    private Component component;
    public Decorator(Component component) {
        this.component = component;
    }

    public void operation(){
        component.operation();
    }
}

class ConcreteDecorator extends Decorator {
    public ConcreteDecorator(Component component) {
        super(component);
    }

    public void operation(){
        super.operation();
        addedBehavior()//在具体装饰类里面可以增加新的行为扩展该方法达到装饰的目的。
    }

    public void addedBehavior() { };
}

class Client {
    public static void main(String args[]) {
        Component component = new ConcreteComponent();
        Component comDecorator = new ConcreteDecorator(component);
        //从上面可以看出 创建的所有对象都可以使用抽象构件来表示,因为都是它的子类,因此对于来说透明。
        comDecorator.operation();
    }
}

https://blog.csdn.net/charce1989/article/details/71190013

3.Facade 外观模式

提供一个统一的接口来取代一系列小接口调用,相当于对复杂系统做了一个封装,简化用户使用。
示例:
在这里插入图片描述
在这里插入图片描述
封装类中的方法一般采用static模式,不需要client端显示构造出被封装类的实例

行为类模式

1.Strategy 策略模式

根据client的需要动态切换算法而不是把算法写死在代码里→为不同的算法构造抽象接口,利用delegation,运行时动态传入client倾向的算法类实例
<黑盒框架使用的方法>
在这里插入图片描述

2.Template Method 模板模式

步骤一样,具体方法不同→共性的步骤在抽象类内公共实现,差异化的步骤在各个子类中实现
<白盒框架使用的方法>
在这里插入图片描述

3.Iterator 迭代器

让自己的集合类实现Iterable接口,并实现自己的独特Iterator迭代器(hasNext, next, remove),允许客户端利用这个迭代器进行显式或隐式的迭代遍历。
Iterable接口:实现该接口的集合对象是可迭代遍历的

public interface Iterable<T> {
	 ... 
	 Iterator<T> iterator();
} 

Iterator接口:迭代器

public interface Iterator<E> {
	boolean hasNext(); 
	E next(); 
	void remove(); 
}

在这里插入图片描述
↑Iterator iter = collection.iterator();

示例:
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值