欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 文旅 > 旅游 > 【设计模式】桥接模式(用于解决在类层次之中产生过多子类的问题)——UnityC#

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

2025/4/30 15:07:48 来源:https://blog.csdn.net/weixin_47220117/article/details/147522226  浏览:    关键词:【设计模式】桥接模式(用于解决在类层次之中产生过多子类的问题)——UnityC#

一种结构型设计模式。

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

优点:

  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();

}

}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词