基于C#的设计模式学习之桥接模式

        桥接模式是一种结构型模式,将抽象与实现与实现分离,使他们可以独立变化,通过组合关系替代继承关系,符合合成复用原则,可以总结为一句话,将m*n个实现类的设计转换成m+n个实现类的设计。

 

namespace Designmode.Bridge
{
    /// <summary>
    /// 颜色的接口
    /// </summary>
    public interface IColor
    {
        /// <summary>
        /// 获取颜色
        /// </summary>
        /// <returns></returns>
        string GetColor();
    }
}
namespace Designmode.Bridge
{
    /// <summary>
    /// 图形抽象类
    /// </summary>
    public abstract class Shape
    {
        /// <summary>
        /// 图形颜色
        /// </summary>
        public IColor Color { set; get; }

        /// <summary>
        /// 设置颜色
        /// </summary>
        /// <param name="color"></param>
        /// <exception cref="NotImplementedException"></exception>
        public  void SetColor(IColor color)
        {
            this.Color = color;
        }

        /// <summary>
        /// 绘制
        /// </summary>
        public abstract void Draw();
    }
}
namespace Designmode.Bridge
{
    /// <summary>
    /// 正方形
    /// </summary>
    public class Square : Shape
    {
        /// <summary>
        /// 绘制
        /// </summary>
        public override void Draw()
        {
            Console.WriteLine($"square with {this.Color.GetColor()}");
        }
    }
}
namespace Designmode.Bridge
{
    public class Circle : Shape
    {
        /// <summary>
        /// 绘制
        /// </summary>
        public override void Draw()
        {
            Console.WriteLine($"Circle with {this.Color}");
        }
    }
}
namespace Designmode.Bridge
{
    /// <summary>
    /// 颜色的具体实现
    /// </summary>
    public class RedColor : IColor
    {
        /// <summary>
        /// 获取颜色
        /// </summary>
        /// <returns></returns>
        public string GetColor()
        {
            return "red";
        }
    }
}
namespace Designmode.Bridge
{
    /// <summary>
    /// 颜色的具体实现
    /// </summary>
    public class GreenColor:IColor
    {
        /// <summary>
        /// 获取颜色
        /// </summary>
        /// <returns></returns>
        public string GetColor()
        {
            return "Green";
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Designmode.Adapter;
using Designmode.Bridge;


namespace Designmode
{
    class Program
    {
        static void Main(string[] args)
        {
            #region 桥接模式
            //红色
            IColor red = new RedColor();
            //红色正方形
            Shape square = new Square();
            square.SetColor(red);
            square.Draw();
            #endregion
        }
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值