介绍:简单工厂模式主要由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: