建造者模式,其实说白了就是将复杂的对象的创建过程抽象出来,针对不同的创建过程,产生不同的对象。
建造者隐藏了产品的产生过程,也就是产生产品的过程,如果要是改变产品的内部表示,只需要在定义一个具体的建造者就可以了。
下面给出UML图:
下面我们使用代码来展示一下建造者模式的使用,很简单的实例,我们以建造楼房为例,讲述建造者模式更为恰当。
首先我们列出抽象的楼房建造者,代码如下:
namespace Builder { public abstract class RoomBuilder { public abstract void CreateRoomFrame(); public abstract void BuilderRoom(); public abstract void DecoratingRoom(); public abstract Room GetRoom(); } }
具体的简单以及复杂楼房建造者的实现,代码如下:
namespace Builder.Concrete { public class SimpleRoomBuilder : RoomBuilder { private Room room = new Room(); public override void CreateRoomFrame() { room.Frame = "Simple Frame"; } public override void BuilderRoom() { room.BuilderMaterial = "No Using Rebar"; } public override void DecoratingRoom() { room.Decorating = "Simple Decorating"; } public override Room GetRoom() { return room; } } }
namespace Builder.Concrete { public class ComplexRoomBuilder : RoomBuilder { private Room room = new Room(); public override void CreateRoomFrame() { room.Frame = "Complex Frame"; } public override void BuilderRoom() { room.BuilderMaterial = "Using Rebar"; } public override void DecoratingRoom() { room.Decorating = "Complex Decorating"; } public override Room GetRoom() { return room; } } }
楼房类的代码如下:
namespace Builder { public class Room { public string Frame { set; get; } public string BuilderMaterial { set; get; } public string Decorating { set; get; } public override string ToString() { return this.Frame + "\r\n" + this.BuilderMaterial + "\r\n" + this.Decorating; } } }
指挥者类的实现
namespace Builder { public class Director { public Director(RoomBuilder builder) { builder.CreateRoomFrame(); builder.BuilderRoom(); builder.DecoratingRoom(); } } }
main方法的实现
namespace Builder { class Program { static void Main(string[] args) { SimpleRoomBuilder concrete1 = new SimpleRoomBuilder(); Director director = new Director(concrete1); Room room = concrete1.GetRoom(); Console.WriteLine(room.ToString()); Console.ReadKey(); } } }
以上就是建造者模式的简单的实例,建造者模式是在当创建复杂对象的算法应该独立于该对象的组成部分以及它们的装配方式时适用的模式。
本篇文章建造者模式至此,谢谢您收看我的博客。