今天看了设计模式中的Bridge模式,所以列出自己对其的认识:
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();
Bridge模式:指的是将一事件的抽象与行为分开来,也就是说使对象的属性与方法之间藕合度降低.
使用Bridge模式的好处:当给对象增加新的属性时只需要继承这个对象的抽象属性接口就行了,当给对象增加新的方法时只需要继承这个对象的抽象方法接口噈OK了。这样就使用一个对象的属性与方法完成分开来了。
现以本人在机子上玩游戏为例来说明Bridge模式:
1.对象属性方面:
先创建一个抽象类来说明在什么系统下玩游戏
再创建具体的属性类如Windows98系统与windows2000系统
2.对象方法方面:
先创建一个抽象来来说明玩游戏
再创建具体的类来说明正在玩什么游戏
接著來看看該如何調用了:
接著來看看該如何調用了:
浙公网安备 33010602011771号