随笔 - 281  文章 - 24 评论 - 43 阅读 - 23万
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

今天看了设计模式中的Bridge模式,所以列出自己对其的认识:

Bridge模式:指的是将一事件的抽象与行为分开来,也就是说使对象的属性与方法之间藕合度降低.

使用Bridge模式的好处:当给对象增加新的属性时只需要继承这个对象的抽象属性接口就行了,当给对象增加新的方法时只需要继承这个对象的抽象方法接口噈OK了。这样就使用一个对象的属性与方法完成分开来了。

现以本人在机子上玩游戏为例来说明Bridge模式:
1.对象属性方面:
先创建一个抽象类来说明在什么系统下玩游戏
再创建具体的属性类如Windows98系统与windows2000系统
2.对象方法方面:
先创建一个抽象来来说明玩游戏
再创建具体的类来说明正在玩什么游戏

using System;

namespace DesignPatterns.BirdgePattern
{
    
/// <summary>
    
/// 定義計算機類型的抽象類(接口)
    
/// </summary>

    abstract public class ComputerSystem
    
{
        
abstract public string PlayGame();
    }

    
/// <summary>
    
/// 定義Windows98系統
    
/// </summary>

    public class Windows98 : ComputerSystem
    
{
        
public override string PlayGame()
        
{
            
return "Window98";
        }

    }

    
/// <summary>
    
/// 定義Windows2000系統
    
/// </summary>

    public class Windows2000 : ComputerSystem
    
{
        
public override string PlayGame()
        
{
            
return "Windows2000";
        }

    }

    
/// <summary>
    
/// 定義游戲的抽象類(接口)
    
/// </summary>

    abstract public class Game
    
{
        
protected ComputerSystem computerSystem;
        
public ComputerSystem SetComputerSystem
        
{
            
set{computerSystem=value;}
        }

        
public abstract string Play();
    }

    
/// <summary>
    
/// 定義星際類
    
/// </summary>

    public class StartCarft : Game
    
{
        
public override string Play()
        
{
            
string systemName = computerSystem.PlayGame();
            
return "正在" + systemName + "系統下玩星際爭霸";
        }

    }

    
/// <summary>
    
/// 定義敵國類
    
/// </summary>

    public class AgeOfEmpire : Game
    
{
        
public override string Play()
        
{
            
string systemName = computerSystem.PlayGame();
            
return "正在" + systemName + "系統下玩帝國時代";
        }

    }

}


接著來看看該如何調用了:
Game objGame = new AgeOfEmpire();// new StartCarft(); //創建所玩游戲的對象
            objGame.SetComputerSystem = new Windows2000();//new Windows98(); //指定是在哪個系統下玩游戲
            label1.Text = objGame.Play();

 

接著來看看該如何調用了:
posted on   阿C's  阅读(173)  评论(1编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 25岁的心里话
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示