디자인 모드 --- 생 성기

6524 단어

기능
    복잡 한 대상 의 구축 과 그 표 시 를 분리 시 켜 같은 구축 과정 에서 서로 다른 표 시 를 만 들 수 있 도록 한다.
2. 예시 코드
namespace DesignPattern_Builder
{
	class Product1 { 
		PartA m_partA;
		PartB m_partB;
		PartC m_partC;
	} ;
	class Product2 {
		PartA m_partA;
		PartB m_partB;
		PartC m_partC;
	} ;

	// class Builder
	class Builder	//    
	{
	public:
		virtual void BuilderPartA() {}	//      
		virtual void BuilderPartB() {}
		virtual void BuilderPartC() {}
	protected:
		Builder() {}
	} ;

	// class ConcreteBuilder1
	class ConcreteBuilder1 : public Builder	//  Product1
	{
	public:
		ConcreteBuilder1() : _product(NULL) {}

		virtual void BuilderPartA() { /*...*/ }	
		virtual void BuilderPartB() { /*...*/ }
		virtual void BuilderPartC() { /*...*/ }

		virtual Product1* GetProduct1() { return _product ; }	//     Product1  
	private:
		Product1 *_product ;
	} ;

	// class ConcreteBuilder2
	class ConcreteBuilder2 : public Builder	//  Product2
	{
	public:
		ConcreteBuilder2() : _product(NULL) {}

		virtual void BuilderPartA() { /*...*/ }	
		virtual void BuilderPartB() { /*...*/ }
		virtual void BuilderPartC() { /*...*/ }

		virtual Product2* GetProduct2() { return _product ; }	//     Product2  
	private:
		Product2 *_product ;
	} ;

	// class Director
	class Director
	{
	public:
		//    (Director                  ,        client  )
		void Construct(Builder *builder)
		{
			builder->BuilderPartA() ;
			builder->BuilderPartB() ;
			builder->BuilderPartC() ;
		}
	} ;
}

     :
{
	using namespace DesignPattern_Builder ;

	Director director ;

	//        
	ConcreteBuilder1 *pBuilder1 = new ConcreteBuilder1() ;
	director.Construct(pBuilder1) ;
	Product1 *product1 = pBuilder1->GetProduct1() ;

	//        
	ConcreteBuilder2 *pBuilder2 = new ConcreteBuilder2() ;
	director.Construct(pBuilder2) ;
	Product2 *product2 = pBuilder2->GetProduct2() ;
}

       “  :                 ,                  。”。           ,        Product1, Product2  2     ,   2      PartA, PartB, PartC      ,    ,      ,     。
  ,           ,  Product1, Product2       ,
director.Construct(pBuilder2) ;
// class Builder
class Builder	//    
{
public:
	virtual void BuilderPartA() {}	//      
	virtual void BuilderPartB() {}
	virtual void BuilderPartC() {}
protected:
	Builder() {}
} ;

class Director
{
public:
	//    (Director                  ,        client  )
	void Construct(Builder *builder)
	{
		builder->BuilderPartA() ;
		builder->BuilderPartB() ;
		builder->BuilderPartC() ;
	}
} ;

             class ConcreteBuilder1, class ConcreteBuilder2  :
virtual void BuilderPartA() { /*...*/ }	
virtual void BuilderPartB() { /*...*/ }
virtual void BuilderPartC() { /*...*/ }

  :            ,    ,           。
  :                    ,             。

좋은 웹페이지 즐겨찾기