设计模式 建造者模式
先写一个建造者的抽象类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BuildPattern
{
abstract class PersonBuilder
{
protected Graphics g;
protected Pen p;
public PersonBuilder(Graphics g, Pen pen)
{
this.g = g;
this.p = pen;
}
public abstract void BuildHead();
public abstract void BuildBody();
public abstract void BuildArmLeft();
public abstract void BuildArmRight();
public abstract void BuildLegLeft();
public abstract void BuildLegRight();
}
}
在写一个建造者的导演类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BuildPattern
{
class PersonDirector
{
private PersonBuilder pb;
public PersonDirector(PersonBuilder pb)
{
this.pb = pb;
}
public void CreatePerson()
{
pb.BuildHead();
pb.BuildBody();
pb.BuildArmLeft();
pb.BuildArmRight();
pb.BuildLegLeft();
pb.BuildLegRight();
}
}
}
在写两个类继承建造者类,只需写一些细节。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BuildPattern
{
class PersonThinBuilder:PersonBuilder
{
public PersonThinBuilder(Graphics g, Pen p) : base(g, p)
{
}
public override void BuildHead()
{
g.DrawEcllipse(p, 50, 20, 30, 30);
}
public override void BuildBody()
{
g.DrawRectangle(p, 60, 50, 10, 50);
}
public override void BuildArmLeft()
{
g.DrawLine(p, 60, 50, 40, 100);
}
public override void BuildArmRight()
{
g.DrawLine(p, 70, 50, 90, 100);
}
public override void BuildLegLeft()
{
g.DrawLine(p, 60, 100, 45, 150);
}
public override void BuildLegRight()
{
g.DrawLine(p, 70, 100, 85, 150);
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BuildPattern
{
class PersonFatBuilder : PersonBuilder
{
public PersonFatBuilder(Graphics g, Pen p) : base(g, p)
{
}
public override void BuildHead()
{
g.DrawEcllipse(p, 50, 20, 30, 30);
}
public override void BuildBody()
{
g.DrawRectangle(p, 60, 50, 100, 80);
}
public override void BuildArmLeft()
{
g.DrawLine(p, 60, 50, 40, 100);
}
public override void BuildArmRight()
{
g.DrawLine(p, 70, 50, 90, 100);
}
public override void BuildLegLeft()
{
g.DrawLine(p, 60, 100, 45, 150);
}
public override void BuildLegRight()
{
g.DrawLine(p, 70, 100, 85, 150);
}
}
}
在写测试类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BuildPattern
{
class Program
{
static void Main(string[] args)
{
Pen p = new Pen(Color.Yellow);
PersonThinBuilder ptb = new PersonThinBuilder(pictureBox1.CreateGraphics(), p);
PersonDirector pdThin = new PersonDirector(ptb);
pdThin.CreatePerson();
PersonFatBuilder pfd=new PersonFatBuilder(pictureBox1.CreateGraphics(), p);
PersonDirector pdFat = new PersonDirector(pfb);
pdFat.CreatePerson();
}
}
}