工厂模式之简单工厂

 

 

   简单工厂模式是属于创建型模式,又叫做静态工厂方法(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();
		}
	}

}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值