Abstract Factory

Abstract Factory
产品抽象类声明产品接口,每个具体产品子类重写该接口。
工厂抽象类声明一系列工厂方法,针对每个产品重写工厂方法,在该工厂方法中创建对应的具体产品。不同的具体工厂类对应不同的产品组合。当有N类产品,每类产品里有M种具体产品对象时,可以产生M*N个具体工厂类。
这样,用户可以使用工厂基类指针调用工厂方法,创建产品,对产品进行操作。
当每一类产品的种类增加时,只需要增加对应的工厂子类,用户针对产品操作的代码保持不变。而且用户并不需要知道它所操作的产品具体是什么。

当需要创建的对象是由若干类对象,并且每类对象又分不同种类时,可以采用Abstact Factory。

#include < iostream >

using   namespace  std;

// 产品1抽象类
class  Student
{
public :
    
virtual   ~ Student(){}
    
// 提供一个接口
     virtual   void  TestStudent()  =   0 ;
};

// 具体产品子类
class  GoodStudent:  public  Student
{
public :
    
// 重写接口
     virtual   void  TestStudent()
    {
        cout
<< " GoodStudent " << endl;
    }
};

// 具体产品子类
class  BadStudent:  public  Student
{
public :
    
// 重写接口
     virtual   void  TestStudent()
    {
        cout
<< " BadStudent " << endl;
    }
};

// 产品2抽象类
class  Teacher
{
public :
    
virtual   ~ Teacher(){}
    
// 提供一个接口
     virtual   void  TestTeacher()  =   0 ;
};

// 具体产品子类
class  GoodTeacher:  public  Teacher
{
public :
    
// 重写接口
     virtual   void  TestTeacher()
    {
        cout
<< " GoodTeacher " << endl;
    }
};

// 具体产品子类
class  BadTeacher:  public  Teacher
{
public :
    
// 重写接口
     virtual   void  TestTeacher()
    {
        cout
<< " BadTeacher " << endl;
    }
};

// 工厂抽象类
class  Factory
{
public :
    
virtual   ~ Factory(){}

    
// 声明工厂方法
     virtual  Teacher *  CreateTeacher()  =   0 ;
    
virtual  Student *  CreateStudent()  =   0 ;
};

// 具体工厂
class  GoodFactory: public  Factory
{
protected :
    
// 重写工厂方法,创建具体产品
    Teacher *  CreateTeacher()
    {
        
return   new  GoodTeacher();
    }
    Student
*  CreateStudent()
    {
        
return   new  GoodStudent();
    }
};

// 具体工厂
class  BadFactory: public  Factory
{
protected :
    
// 重写工厂方法,创建具体产品
    Teacher *  CreateTeacher()
    {
        
return   new  BadTeacher();
    }
    Student
*  CreateStudent()
    {
        
return   new  BadStudent();
    }
};

// 用户代码,传入工厂
// 根据需要创建产品,对产品进行操作
void  ClinetTest(Factory  * p)
{
    Teacher 
* pt  =  p -> CreateTeacher();
    Student 
* ps  =  p -> CreateStudent();
    pt
-> TestTeacher();
    ps
-> TestStudent();
    delete pt;
    delete ps;
}

int  main()
{
    
// 创建具体工厂
    Factory  * pg  =   new  GoodFactory;
    Factory 
* pb  =   new  BadFactory;

    ClinetTest(pg);
    ClinetTest(pb);

    
// 销毁工厂
    delete pg;
    delete pb;
    
    
return   0 ;
}


你可能感兴趣的:(Abstract Factory)