抽象工廠模式(abstract)創建型模式 c#簡單例子
適用於玩家用戶數play1、play2....有變化,而行為move、jum無變化時
玩家playone的行為:向左移動和向上跳躍
玩家playtwo的行為:向右移動和向下跳躍
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace adapterpattern { public partial class abstractForm : Form { public abstractForm() { InitializeComponent(); } private void btnDisplay_Click(object sender, EventArgs e) { playFactory pf1 = new playone();//隱藏行為move和jump. playWorld p1 = new playWorld(pf1);//行為向左移動和向上跳躍 this.listBox1.Items.Add(p1.createPlay()); playWorld p2 = new playWorld(new playtwo());//行為向右移動和向下跳躍 this.listBox1.Items.Add(p2.createPlay()); } } public class playWorld//實體工廠和抽象工廠的交接 { imove move; ijump jump; public playWorld(playFactory pp) { this.move = pp.move(); this.jump = pp.jump(); } public string createPlay() { move.move(); jump.jump(); return move.movestring + jump.jumpstring; } } public abstract class playFactory//抽象工廠 { public abstract imove move(); public abstract ijump jump(); } public class playone : playFactory//抽象工廠實例1 { public override imove move() { return new leftmove(); } public override ijump jump() { return new topJump(); } } public class playtwo : playFactory//抽象工廠實例2 { public override imove move() { return new rightmove(); } public override ijump jump() { return new downJump(); } } public abstract class imove//抽象行為imove { public string movestring; public abstract void move(); } public abstract class ijump//抽象行為jump { public string jumpstring; public abstract void jump(); } public class leftmove : imove//move行為實例1 { public override void move() { movestring = "左移動"; } } public class rightmove : imove//move行為實例2 { public override void move() { movestring = "右移動"; } } public class topJump : ijump//jump行為實例1 { public override void jump() { jumpstring = "向上跳"; } } public class downJump : ijump//jump行為實例2 { public override void jump() { jumpstring = "向下跳"; } } }當需要增加新玩家時,只要再增加一個繼承playfacotry的類,其他都不需要改動
新玩家行為:向左移動和向下跳躍
public class newplay:playFactory//新增加玩家:向左移動和向下跳躍 { public override imove move() { return new leftmove(); } public override ijump jump() { return new downJump(); } }
playWorld newp = new playWorld(new newplay());
this.listBox1 .Items .Add (newp .createPlay ());