理解:构建一个产品的步骤是稳定的,但是每个产品因为每一步的不同而产生出不同形状。比如台球的一次击打过程就是一个产品,产品的过程包括“瞄准--运杆--出杆”三个步骤。虽然我和丁俊晖都要执行这三个步骤,但是每一步小丁做得都比我好,所以小丁的这次击打肯定就比我的好。
代码:
using System.Collections.Generic;
using System.Windows.Forms;
namespace DesignMode.Builder
{
public class OneBreak
{
IList<string> _flow = new List<string>();
public void AddParts(string step)
{
_flow.Add(step);
}
public void Show()
{
foreach (string s in _flow)
{
MessageBox.Show(s);
}
}
}
public abstract class Break
{
public abstract void Aim();
public abstract void RunStick();
public abstract void Shot();
public abstract OneBreak GetBreak();
}
public class ME_Break : Break
{
private OneBreak flow = new OneBreak();
public override void Aim()
{
flow.AddParts("瞄偏了");
}
public override void RunStick()
{
flow.AddParts("运球姿势不对");
}
public override void Shot()
{
flow.AddParts("发力太轻了");
}
public override OneBreak GetBreak()
{
return flow;
}
}
public class DING_Break : Break
{
private OneBreak flow = new OneBreak();
public override void Aim()
{
flow.AddParts("瞄得很准");
}
public override void Shot()
{
flow.AddParts("发力刚刚好");
}
public override void RunStick()
{
flow.AddParts("运球很标准");
}
public override OneBreak GetBreak()
{
return flow;
}
}
//固定步骤类,相当于建造指挥者
public class FixStep
{
public void RunStep(Break _break)
{
_break.Aim();
_break.RunStick();
_break.Shot();
}
}}
using System.Windows.Forms;
namespace DesignMode.Builder
{
public class OneBreak
{
IList<string> _flow = new List<string>();
public void AddParts(string step)
{
_flow.Add(step);
}
public void Show()
{
foreach (string s in _flow)
{
MessageBox.Show(s);
}
}
}
public abstract class Break
{
public abstract void Aim();
public abstract void RunStick();
public abstract void Shot();
public abstract OneBreak GetBreak();
}
public class ME_Break : Break
{
private OneBreak flow = new OneBreak();
public override void Aim()
{
flow.AddParts("瞄偏了");
}
public override void RunStick()
{
flow.AddParts("运球姿势不对");
}
public override void Shot()
{
flow.AddParts("发力太轻了");
}
public override OneBreak GetBreak()
{
return flow;
}
}
public class DING_Break : Break
{
private OneBreak flow = new OneBreak();
public override void Aim()
{
flow.AddParts("瞄得很准");
}
public override void Shot()
{
flow.AddParts("发力刚刚好");
}
public override void RunStick()
{
flow.AddParts("运球很标准");
}
public override OneBreak GetBreak()
{
return flow;
}
}
//固定步骤类,相当于建造指挥者
public class FixStep
{
public void RunStep(Break _break)
{
_break.Aim();
_break.RunStick();
_break.Shot();
}
}}
客户端代码:
private void btn_Builder_Click(object sender, EventArgs e)
{
//列出不同建造者
ME_Break me = new ME_Break();
DING_Break ding = new DING_Break();
//告诉指挥者用哪个来建造
FixStep step = new FixStep();
step.RunStep(ding);
//建造完成后再获取建造对象
OneBreak flow = ding.GetBreak();
flow.Show();}
{
//列出不同建造者
ME_Break me = new ME_Break();
DING_Break ding = new DING_Break();
//告诉指挥者用哪个来建造
FixStep step = new FixStep();
step.RunStep(ding);
//建造完成后再获取建造对象
OneBreak flow = ding.GetBreak();
flow.Show();}