程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> 關於C語言 >> C#設計模式之建造者設計模式(Builder)(2)

C#設計模式之建造者設計模式(Builder)(2)

編輯:關於C語言

三、程序舉例:

該程序演示了Builder模式一步一步完成構件復雜產品的過程。用戶可以控制生成過程以及生成不同對象。

// Builder pattern -- Structural example 
using System;
using System.Collections;
// "Director"
class Director
{
 // Methods
 public void Construct( Builder builder )
 {
  builder.BuildPartA();
  builder.BuildPartB();
 }
}
// "Builder"
abstract class Builder
{
 // Methods
 abstract public void BuildPartA();
 abstract public void BuildPartB();
 abstract public Product GetResult();
}
// "ConcreteBuilder1"
class ConcreteBuilder1 : Builder
{
 // FIElds
 private Product product;
 // Methods
 override public void BuildPartA()
 {
  product = new Product();
  product.Add( "PartA" );
 }
 override public void BuildPartB()
 {
  product.Add( "PartB" );
 }
 override public Product GetResult()
 {
  return product;
 }
}
// "ConcreteBuilder2"
class ConcreteBuilder2 : Builder
{
 // FIElds
 private Product product;
 // Methods
 override public void BuildPartA()
 {
  product = new Product();
  product.Add( "PartX" );
 }
 override public void BuildPartB()
 {
  product.Add( "PartY" );
 }
 override public Product GetResult()
 {
  return product;
 }
}
// "Product"
class Product
{
 // FIElds
 ArrayList parts = new ArrayList();
 // Methods
 public void Add( string part )
 {
  parts.Add( part );
 }
 public void Show()
 {
  Console.WriteLine( " Product Parts -------" );
  foreach( string part in parts )
   Console.WriteLine( part );
 }
}
/**//// <summary>
/// ClIEnt test
/// </summary>
public class ClIEnt
{
 public static void Main( string[] args )
 {
  // Create director and builders
  Director director = new Director( );
  Builder b1 = new ConcreteBuilder1();
  Builder b2 = new ConcreteBuilder2();
  // Construct two products
  director.Construct( b1 );
  Product p1 = b1.GetResult();
  p1.Show();
  director.Construct( b2 );
  Product p2 = b2.GetResult();
  p2.Show();
 }
}

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved