一 概要
1.1 结构型模式
- 关注类和对象的组合。继承的概念被用来组合接口和定义组合对象,从而获得新功能。
1.2 定义
- 将抽象与实现分离,使它们可以独立变化。它是用组合关系代替继承关系来实现,从而降低了抽象和实现这两个可变维度的耦合度。
二 UML类图
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/39a2323025421692f7804296d02756a9.png)
三 例子
class Program
{
static void Main(string[] args)
{
Abstraction abstraction = new AbstractionA();
abstraction.SetImplementor(new ImplementorA());
abstraction.Operation();
}
}
public interface Implementor
{
void OperationImp();
}
public abstract class Abstraction
{
protected Implementor implementor;
public void SetImplementor(Implementor implementor)
{
this.implementor = implementor;
}
public abstract void Operation();
}
public class ImplementorA : Implementor
{
public void OperationImp()
{
}
}
public class ImplementorB : Implementor
{
public void OperationImp()
{
}
}
public class AbstractionA : Abstraction
{
public override void Operation()
{
if (this.implementor == null) return;
this.implementor.OperationImp();
}
}
四 优缺点
4.1 优点
- 将抽象部分和它的实现部分分离, 使它们都可以独立地变化。并且各自的变化不会影响其他独立出来的模块的实现。
- 符合依赖倒转原则以及里氏代换原则。
- 低耦合。
4.2 缺点
- 增加系统复杂度。
五 使用场景
- 当一个类存在两个独立变化的维度,且这两个维度都需要进行扩展时。
- 当一个系统不希望使用继承或因为多层次继承导致系统类的个数急剧增加时。
- 当一个系统需要在构件的抽象化角色和具体化角色之间增加更多的灵活性时。