跟小D每日学口语

设计模式之建造者模式代码示例

using System;
using System.Collections;
using System.Collections.Generic;

namespace BuilderFunc{

    public class Product{

        List<string> arrList = new List<string>();
        // First in First Out (FIFO) 
        Queue  Q = new Queue(); 
        
        // Last in First out (LIFO) 
        Stack S = new Stack();
        public void Add(string param)
        {
            arrList.Add(param);
        }

        public void AddEvent(EventArgs e)
        {
            Q.Enqueue(e);
        }
        
        public void Show() { 
            Console.WriteLine("\nProduct Param -------"); 
            foreach (string part in arrList) 
                Console.WriteLine(part); 
                
            foreach (EventArgs e in Q) 
                Console.WriteLine(e); 
        }
    }

    public abstract class AbstractBuilder{
        public abstract void BuilderProductA();
        public abstract void BuilderProductB();
        public abstract Product GetResult();
    }

    public class ConcreteBuilder1 : AbstractBuilder{

        private Product product = new Product();

        public override void BuilderProductA(){
            product.Add(this.ToString() + " : BuilderProductA");
        }
        public override void BuilderProductB(){
            product.Add(this.ToString() + " : BuilderProductB");
        }
        public override Product GetResult(){
            return product;
        }
    }

    public class Director{
        public static void CreateBuilder(AbstractBuilder abstractBuilder)
        {
            abstractBuilder.BuilderProductA();
            abstractBuilder.BuilderProductB();
        }
    }

    public class EntryPoint{
        public static void Main(string[] args){
            AbstractBuilder absBuilder = new ConcreteBuilder1();
            Director.CreateBuilder(absBuilder);
            Product p1 = absBuilder.GetResult();
            p1.Show();
            Console.Read();
        }
    }
}
posted @ 2012-08-22 23:35  Danny Chen  阅读(290)  评论(0编辑  收藏  举报