今天来复习一下Java设计模式中的工厂模式,工厂模式可以动态决定将哪一个类实例化,不必事先知道每次要实例化哪个类。包含几下几种形态:
- 简单工厂模式,又称静态工厂模式;
- 工厂方法模式
- 抽象化模式
简单工厂模式
简单工厂模式是类的创建模式,根据传入的参数决定生产怎样的产品,结构如下:
简单工厂模式包含工厂角色、抽象产品角色和具体产品角色;
下面以一个水果的例子来说明简单工厂模式:
首先设计水果的生命周期的接口:
/**
* 产品的接口
*
* @author Administrator
*
*/
public interface Fruit {
/**
* 种植
*/
void plant();
/**
* 生长
*/
void grow();
/**
* 收获
*/
void harvest();
}
然后具体的水果的具体生命周期中的行为,以及自个的特性:
/**
* 具体的产品
*
* @author Administrator
*
*/
public class Apple implements Fruit {
/**
* 每种产品自有的特性
* 顏色
*/
private int appleColor;
public int getAppleColor() {
return appleColor;
}
public Apple setAppleColor(int appleColor) {
this.appleColor = appleColor;
return this;
}
@Override
public void plant() {
// TODO Auto-generated method stub
System.out.println("Apple has been planted");
}
@Override
public void grow() {
// TODO Auto-generated method stub
System.out.println("Apple is growing");
}
@Override
public void harvest() {
// TODO Auto-generated method stub
System.out.println("Apple has been harvested");
}
}
最后在肥沃的土壤中生长吧:
/**
* 生产产品的工厂
*
* @author Administrator
*
*/
public class FruitFactory {
public static Fruit createFruit(String type) {
if (type.equals("Apple")) {
return new Apple();
}
if (type.equals("WaterMelon")) {
return new WaterMelon().setHasSeed(true);
}
return null;
}
}
测试一下我们的水果是怎样的:
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
WaterMelon fruit = (WaterMelon) FruitFactory.createFruit("WaterMelon");
fruit.plant();
fruit.grow();
fruit.harvest();
System.out.println("WaterMelon is has seed:"+fruit.isHasSeed());
}
}
结果:
WaterMelon has been planted
WaterMelon is growing
WaterMelon has been harvested
WaterMelon is has seed:true
优缺点
-优点
核心是工厂类,该类有必要的逻辑判断,可以决定什么时候创建特定的实例,客户端不用关心怎么创建,只需要拿到这个实例就行了,做到了对责任的分割;
-缺点
当产品类有复杂的多层次的等级结构时,工厂类势必会狠臃肿,这就需要我们用工厂方法模式啦:
okay:一个简单的工厂模式就这样完成了;
630

被折叠的 条评论
为什么被折叠?



