2.简单工厂模式(Simple Factory)

介绍:简单工厂模式主要由3部分组成:工厂类、抽象类和实现抽象类的具体类

 

优点:客户端不再负责对象的创建,把这个责任丢给了具体的工厂类,客户端只负责对对象的调用,从而明确了各个类的职责.

 

缺点:使用了静态方法来创建对象,导致静态方法无法被继承.

 

例子:

 

 

package com.samplefactory;

public interface Animal {
	/**动物都会吃的*/
	public void eat();
}

 

 

package com.samplefactory;

public class Tiger implements Animal{

	public void eat() {
		System.out.println("老虎会吃.");
		
	}
	
	public void run(){
		System.out.println("老虎会跑.");
	}
	

}

 

package com.samplefactory;

public class Dolphin implements Animal {

	public void eat() {
		System.out.println("海豚会吃.");
		
	}
	
	public void swim(){
		System.out.println("海豚会游泳.");
	}

}

 

 

 

package com.samplefactory;

/**
 * 
 * @Title: SampleFactory.java
 * @Description: TODO(动物的简单工厂)
*/
public class SampleFactory {

	public static Animal createAnimal(String name) {
		if ("Tiger".equals(name)) {
			return new Tiger();
		} else if ("Dolphin".equals(name)) {
			return new Dolphin();
		}else{
			return null;
		}

	}

}

 

 

 

package com.samplefactory;

/**
 * 
 * @Title: Client.java
 * @Description: TODO(客户类)
 * @author awfhome@163.com 
 * @date 2010-6-2 
 * @version V1.0
 */
public class Client {
	
	public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException{
		Animal animal = SampleFactory.createAnimal("Tiger");
		animal.eat();
		
		animal = SampleFactory.createAnimal("Dolphin");
		animal.eat();
		
		//利用反射
		animal = SampleFactory2.createAnimal("com.samplefactory.Tiger");
		animal.eat();
		
	}

}

 

 

改进工厂类:

 

package com.samplefactory;

/**
 * 
 * @Title: SampleFactory2.java
 * @Description: TODO(利用反射来创建类)
 * @author awfhome@163.com 
 * @date 2010-6-2 
 * @version V1.0
 */
public class SampleFactory2 {
	
	public static Animal createAnimal(String name) throws ClassNotFoundException, InstantiationException, IllegalAccessException{
		
		Class c = Class.forName(name);
		Animal animal = (Animal)c.newInstance();
		
		return animal;
		
	}

}

 

 

UML:

 



 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值