简单工厂模式是属于创建型模式,又叫做静态工厂方法(Static Factory Method)模式,但不属于23种GOF设计模式之一。
假如一个农场中FruitFactory生产Apple与Bananer两种水果,当农夫需要采集Apple时,则得到Apple,当需要采集Bananer时,得到Bananer,农场是负责农夫的请求返回想相应的水果。
先用C++来实现一次.
#ifndef _FRUIT_H
#define _FRUIT_H
class Fruit
{
public:
/**
* 采集水果的方法
*/
virtual void get()=0;
Fruit();
~Fruit();
protected:
private:
};
class Apple:public Fruit
{
public:
void get();
Apple();
~Apple();
protected:
private:
};
class Bananer:public Fruit
{
public:
void get();
Bananer();
~Bananer();
protected:
private:
};
#endif
#include "Fruit.h"
#include <iostream>
using namespace std;
Fruit::Fruit()
{
}
Fruit::~Fruit()
{
}
Apple::Apple()
{
}
Apple::~Apple()
{
}
void Apple::get()
{
cout << "采集苹果!" << endl;
}
Bananer::Bananer()
{
}
Bananer::~Bananer()
{
}
void Bananer::get()
{
cout << "采集香蕉!" << endl;
}
#ifndef _FRUITFACTORY_H
#define _FRUITFACTORY_H
#include <iostream>
#include <string>
using namespace std;
class Fruit;
class FruitFactory
{
public:
FruitFactory();
~FruitFactory();
Fruit* getFruit(string typeFruit);
protected:
private:
};
#endif
#include "Fruit.h"
#include "FruitFactory.h"
#include <iostream>
#include <string>
using namespace std;
FruitFactory::FruitFactory()
{
}
FruitFactory::~FruitFactory()
{
}
Fruit* FruitFactory::getFruit(string typeFruit)
{
if (typeFruit == "Apple")
{
return new Apple();
} else {
return new Bananer();
}
}
#include "Fruit.h"
#include "FruitFactory.h"
#include <iostream>
using namespace std;
int main(int argc, char argv[])
{
FruitFactory* factory = new FruitFactory();
Fruit* apple = factory->getFruit("Apple");
apple->get();
Fruit* bananer = factory->getFruit("Bananer");
bananer->get();
return 0;
}
在用Java看看
package sampleFactory;
/**
* 水果工厂
* @author Tankiy
*
*/
public interface Fruit {
/**
* 采集水果的方法
*/
public void get();
}
package sampleFactory;
/**
* 苹果
* @author Tankiy
*
*/
public class Apple implements Fruit {
public void get() {
System.err.println("采集苹果!");
}
}
package sampleFactory;
public class Bananer implements Fruit {
public void get() {
System.err.println("采集香蕉!");
}
}
package sampleFactory;
public class FruitFactory {
/**
* 获取水果
* @param type
* @return
*/
public static Fruit getFruit(String type) throws Exception {
Class fruit = Class.forName(type);
return (Fruit)fruit.newInstance();
}
}
package sampleFactory;
public class FactoryTest {
/**
* @param args
*/
public static void main(String[] args) {
try {
Fruit apple = FruitFactory.getFruit("Apple");
apple.get();
} catch (Exception e) {
e.printStackTrace();
}
}
}