Java工厂设计模式

工厂模式的核心思想就是把创建对象和使用对象解藕,由工厂负责对象的创建,而用户只能通过接口来使用对象,这样就可以灵活应对变化的业务需求,方便代码管理、避免代码重复。

1.工厂设计模式的例子:水果,苹果和橘子

程序在接口和子类之间加入一个过渡类,通过此过渡类端取得接口的实例化对象,一般都会称这个过渡端为工厂类

interface Fruit{
	public void eat();
}

// Apple类实现了Fruit接口
class Apple implements Fruit{

	@Override
	public void eat() {
		System.out.println("eat apple!");
	}
	
}

// Orange类实现了Fruit接口
class Orange implements Fruit{

	@Override
	public void eat() {
		System.out.println("eat orange!");
	}
	
}

// 定义工厂类
class Factory{
	public static Fruit getInstance(String className){
		Fruit f = null;							//定义接口对象
		if("apple".equals(className)){			//判断是哪个类的标记
			f = new Apple();
		}
		if("orange".equals(className)){			//判断是哪个类的标记
			f = new Orange();
		}
		return f;
	}
}

public class factory {

	public static void main(String[] args) {
		Fruit f = null;							//定义接口对象
		f = Factory.getInstance("apple");		//通过工厂取得实例
		f.eat();								//调用方法
	}

}

2.将反射应用在工厂模式上

为了能不修改工厂方法

interface Fruit{
	public void eat();
}

class Apple implements Fruit{

	@Override
	public void eat() {
		System.out.println("eat apple!");
	}
	
}

class Orange implements Fruit{

	@Override
	public void eat() {
		System.out.println("eat orange!");
	}
	
}

// 定义工厂类
class Factory{
	public static Fruit getInstance(String className){
		Fruit f = null;			//定义接口对象
		try{
			f = (Fruit)Class.forName(className).newInstance();	//实例化对象
		}catch(Exception e){
			e.printStackTrace();
		}
		return f;
	}
}

public class factory {

	public static void main(String[] args) {
		Fruit f = null;							//定义接口对象
		f = Factory.getInstance("Apple");		//通过工厂取得实例
		f.eat();								//调用方法
	}

}

3.结合属性文件的工厂模式

 

 

posted @ 2016-03-04 10:51  tonglin0325  阅读(315)  评论(0编辑  收藏  举报