【设计模式】桥接模式(用于解决在类层次之中产生过多子类的问题)——Unity&&C#

一种结构型设计模式。

特点:将实现与抽象分离。

优点:

  1. 分离了实现类和抽象类,使类之间可以进行独立变化,降低了耦合度;
  2. 提高了扩展性;
  3. 为设计提供了清晰的结构;
  4. 可以减少类的数量。

缺点:

  1. 引入了抽象的层次,增加了层次的复杂性。

适用场景:

  1. 需要进行解耦抽象的场景;
  2. 希望避免创建过多子类的场景。

示例:

using System;

/// <summary>

/// 颜色接口类

/// </summary>

public interface IColor

{

string Fill();

}

/// <summary>

/// 形状抽象类

/// </summary>

public abstract class Shape

{

protected IColor color;

protected Shape(IColor color)

{

this.color = color;

}

public abstract void Draw();

}

/// <summary>

/// 红色实现

/// </summary>

public class Red : IColor

{

public string Fill()

{

return "Red";

}

}

/// <summary>

/// 蓝色实现

/// </summary>

public class Blue : IColor

{

public string Fill()

{

return "blue";

}

}

/// <summary>

/// 正方体实现类

/// </summary>

public class Cube : Shape

{

public Cube(IColor color): base(color)

{

}

public override void Draw()

{

Console.WriteLine("绘制了一个" + color.Fill() + "Cube");

}

}

/// <summary>

/// 球体实现类

/// </summary>

public class Sphere : Shape

{

public Sphere(IColor color) : base(color)

{

}

public override void Draw()

{

Console.WriteLine("绘制了一个" + color.Fill() + "Sphere");

}

}

/// <summary>

/// 客户端

/// </summary>

public class Client

{

public static void Main(string[] args)

{

//创建颜色

IColor red = new Red();

IColor blue = new Blue();

//创建形状

Shape cube = new Cube(red);

Shape sphere = new Sphere(blue);

//绘制形状

cube.Draw();

sphere.Draw();

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值