7、生成器模式
7、生成器模式 一种的材料,不同生产者通过同样的加工步骤生成不同的产品 (指导者通过不同的加工步骤,又可以生成不同的产品)——构建复杂的产品, 产品构建和表现的分离
作用:程序结构松散、扩展更容易、复用性更好,代码更清晰、意图更明确
namespace SJ.DesignMode { /// <summary> /// 设计模式 /// </summary> class Program { static void Main(string[] args) { string title = "title"; string body = "body"; string footer = "footer"; //IBuilder ibuilder = new TxtBuilder(); IBuilder ibuilder = new Xmluilder(); Builder builder = new Builder(ibuilder); string end = builder.Create(title, body, footer); Console.WriteLine(end); } } public class Builder { private IBuilder _builder; public Builder(IBuilder builder) { _builder = builder; } public string Create(string title, string body, string footer) { //生成器 执行同样的加工步骤 _builder.Head(title); _builder.Body(body); _builder.Footer(footer); return _builder.GetEnd(); } } public interface IBuilder { void Head(string head); void Body(string body); void Footer(string footer); string GetEnd(); } public class TxtBuilder : IBuilder { private StringBuilder sb = new StringBuilder(); public void Body(string body) { sb.Append("body /r/n"); } public void Footer(string footer) { sb.Append("footer /r/n"); } public string GetEnd() { return sb.ToString(); } public void Head(string head) { sb.Append("head /r/n"); } } public class Xmluilder : IBuilder { private StringBuilder sb = new StringBuilder(); public void Body(string body) { sb.Append("<body> body </body> /r/n"); } public void Footer(string footer) { sb.Append("<Footer> footer </Footer> /r/n"); } public string GetEnd() { return sb.ToString(); } public void Head(string head) { sb.Append("<Head> head </Head> /r/n"); } } }