简单工厂模式属于类的创建型模式,又叫做静态工厂方法模式。通过专门定义一个类来负责创建其他类的实例,被创建的实例通常都具有共同的父类。
所以最少有三个类,一个实例化类,一个实例化类的接口,一个工厂类。其中最核心的是工厂类,它包含必要的判断逻辑,能够根据外界给定的信息,决定究竟应该创建哪个具体类的对象。
优点是用户在使用时可以直接根据工厂类去创建所需的实例,而无需了解这些对象是如何创建以及如何组织的。有利于整个软件体系结构的优化。
缺点是由于工厂类集中了所有实例的创建逻辑,所以“高内聚”方面做的并不好。另外,当系统中的具体产品类不断增多时,可能会出现要求工厂类也要做相应的修改,扩展性并不很好。
看代码:
1,接口类Fruit
public interface Fruit {
public void get();
}
2,实例化类Apple,Banana
public class Apple implements Fruit{
public void get() {
System.out.println("生产苹果");
}
public class Banana implements Fruit{
public void get() {
System.out.println("生产香蕉");
}
}
3,工厂类FruitFactory
public class FruitFactory {
/*
* 获取Apple实例,一般的写法
*/
public static Fruit getApple(){
return new Apple();
}
public static Fruit getBanana(){
return new Banana();
}
/*
* get方法,获取所有产品对象,必须知道实例的名称,可以忽略大小写
*/
public static Fruit getFruit(String type) throws InstantiationException, IllegalAccessException{
if(type.equalsIgnoreCase("apple")){
return Apple.class.newInstance();
}else if(type.equalsIgnoreCase("banana")){
return Banana.class.newInstance();
}else{
System.out.println("找不到对应的实例化类");
return null;
}
}
}
4,测试代码:
public class Test {
public static void main(String[] args) throws InstantiationException, IllegalAccessException {
/*
* 不用工厂,多态的写法
*/
Fruit apple1 = new Apple();
apple1.get();
Fruit b1 =new Banana();
b1.get();
//基本的获取对象的写法
Fruit apple2=FruitFactory.getApple();
apple2.get();
Fruit b2 = FruitFactory.getBanana();
b2.get();
Fruit apple3= FruitFactory.getFruit("apple");
Fruit banana3 = FruitFactory.getFruit("banana");
Fruit banana4 = FruitFactory.getFruit("canana");
apple3.get();
banana3.get();
}
}
}