三种工厂模式
三种工厂模式
#include<iostream>
//简单工厂模式 没有开闭原则 需要自己去判断创建了什么类
/*
class AbstractFruit
{
public:
virtual void Showname() = 0;
};
class Apple : public AbstractFruit
{
public:
virtual void Showname()
{
std::cout << "我是苹果" << std::endl;
}
};
class Pear : public AbstractFruit
{
public:
virtual void Showname()
{
std::cout << "我是鸭梨" << std::endl;
}
};
class Peach : public AbstractFruit
{
public:
virtual void Showname()
{
std::cout << "我是桃子" << std::endl;
}
};
//定义水果工厂
class Factory
{
public:
static AbstractFruit* CreateFruit(std::string flag)
{
if(flag == "apple")
{
return new Apple;
}
else if(flag == "Pear")
{
return new Pear;
}
else if(flag == "peach")
{
return new Peach;
}
}
};
*/
/*
//定义水果基类和抽象水果
class AbstractFruit
{
public:
virtual void Showname() = 0;
};
class Appale : public AbstractFruit
{
public:
virtual void Showname()
{
std::cout << "我是Apple" << std::endl;
}
};
class Pear : public AbstractFruit
{
public:
virtual void Showname()
{
std::cout << "我是Pear" << std::endl;
}
};
//定义抽象工厂
class AbstractFuritFactory
{
public:
virtual AbstractFruit* CreaterFruit() = 0;
};
class AppleFactory:public AbstractFuritFactory
{
virtual AbstractFruit* CreaterFruit()
{
return new Appale;
}
};
class PearFactory:public AbstractFuritFactory
{
virtual AbstractFruit* CreaterFruit()
{
return new Pear;
}
};
*/
// 抽象工厂
class AbstractFruit
{
public:
virtual void operation() = 0;
};
class Apple:public AbstractFruit
{
public:
void operation()
{
std::cout << "this is Apple" << std::endl;
}
};
class Banana:public AbstractFruit
{
public:
void operation()
{
std::cout << "this is Banana" << std::endl;
}
};
class AbstractFactory
{
public:
virtual AbstractFruit* CreateFruit() = 0;
};
//按照地域类型抽象 比如水果分为有核水果和没核水果
class AFactory:public AbstractFactory
{
AbstractFruit* CreateFruit()
{
return new Banana();
}
};
int main()
{
/*工厂
AbstractFuritFactory* factory = nullptr;
AbstractFruit* fruit = nullptr;
factory = new AppleFactory();
fruit = factory->CreaterFruit();
*/
factory = new Afactory();
Banana = factory->CreateFruit();
Banana->operation();
return 0;
}