/**
* 工厂类:用于连接接口和子类,尽量减少客户端的复杂性
* 2017-08-25
* @author Junwei Zhu
*
*/
interface Fruit
{
public void eat();
}
//工厂类:用于连接接口和子类,可以被客户端看到
class Factory
{
public static Fruit getInstance(String className)
{
if("apple".equals(className))
{
return new Apple();
}
else if("orange".equals(className))
{
return new Orange();
}
else return null;
}
}
class Apple implements Fruit
{
public void eat()
{
System.out.println("吃苹果。");
}
}
class Orange implements Fruit
{
public void eat()
{
System.out.println("吃橘子。");
}
}
public class TestFactory
{
public static void main(String[] args)
{
//客户端仅做及少量的修改变可实现多个子类对象的生成
Fruit f = Factory.getInstance("apple");
f.eat();
}
}