/**
* @function
* @version 2015年1月29日 下午7:30:12
*/
public class Main {
public static void main(String[]args){
try {
//直接跟工厂要一个苹果,工厂就给你造一个苹果
Fruit apple = FruitFactory.createFruit("apple");
apple.getSelf();//查看下水果都有的属性
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
/**
* 模拟产品特性
* 水果
* @author tj
*
*/
interface Fruit{
void getSelf();//模拟个产品的特性,例如获取自身的名字
}
/**
* 水果工厂
* @author tj
*
*/
class FruitFactory{
//生产水果的方法
public static Fruit createFruit(String fruit) throws Exception{
if(fruit.equalsIgnoreCase("apple"))
return new Apple();
else if(fruit.equalsIgnoreCase("pear"))
return new Pear();
else
throw new Exception();
}
}
//实例水果,
class Pear implements Fruit{
@Override
public void getSelf() {
// TODO Auto-generated method stub
System.out.println(this.getClass().getName());
}
}
//实例水果
class Apple implements Fruit{
@Override
public void getSelf() {
System.out.println(this.getClass().getName());
}
}
考虑设计模式的之前
应该先考虑简单工厂模式能解决什么问题
毕竟应该是先有问题 后有解决方案 然后就是出现简单工厂模式这种设计模式
简单工厂模式能解决的问题 目前理解是 可以将类的实例化延迟
贴代码