建造者模式
namespace 建造者模式
{
//现在要建造一个房子,需要请设计师和工人,工人负责
class Program
{
static void Main(string[] args)
{
Works works = new Works();//请工人来
Designer designer = new Designer();//请设计师来
designer.Order(works);//设计师下令造房子
Room room = works.getRoom();
if (room == null)
{
Console.WriteLine("房子建造失败");
}
else
Console.WriteLine("房子建造成功");
Console.ReadLine();
}
}
public class Base
{
public Base()
{
Console.WriteLine("地基打好了");
}
}
public class Wall
{
public Wall()
{
Console.WriteLine("墙壁立起了");
}
}
public class Window
{
public Window()
{
Console.WriteLine("窗户装好了");
}
}
public class Roof
{
public Roof()
{
Console.WriteLine("房顶盖好了");
}
}
public class Room
{
Base _Base;
Wall _Wall;
Window _Window;
Roof _Roof;
public Room(Base _base, Wall _wall, Window _window, Roof _roof)
{
_Base =_base;
_Wall =_wall;
_Window =_window;
_Roof = _roof;
}
}
public interface IWorks
{
void BuildBase();
void BuildWall();
void BuildWindow();
void BuildRoof();
Room getRoom();
}
public class Works : IWorks
{
Roof _roof;
Window _window;
Base _base;
Wall _wall;
public void BuildBase()
{
_base = new Base();
}
public void BuildWall()
{
_wall = new Wall();
}
public void BuildWindow()
{
_window = new Window();
}
public void BuildRoof()
{
_roof = new Roof();
}
public Room getRoom()
{
if (_roof == null || _wall == null || _window == null || _base == null)
return null;
return new Room(_base, _wall, _window, _roof);
}
}
public class Designer
{
public void Order(Works works)
{
works.BuildBase();
works.BuildRoof ();
works.BuildWall ();
works.BuildWindow ();
}
}
}