. 良好的编程风格:
客户端(该实例为主方法)调用简单,不需要关注细节,
.程序修改代码,不影响,不影响客户端调用,即使用者不用担心代码变更,因为一个接口可能有多个子类
package org.java.factory;
/**
*
* 该程序是未采用工厂模式,用来对比工厂模式
* @author coder
*因为一个接口可能有多个子类,如果我们在程序上多实现了很多接口,那么我们是需要在
*main方法中(客户端)也相应的需要去new相应接口对象的实例,就会修改客户端代码
*而采用工厂模式则不会,客户端不会去关注子类,也不需要关注factory的处理,只需要
*如何取得对象的接口并操作(详情看下例)
*/
interface Fruit{
public void eat();
}
class Apple implements Fruit{
public void eat() {
System.out.println("***吃苹果");
}
}
class Orange implements Fruit{
@Override
public void eat() {
// TODO Auto-generated method stub
System.out.println("*****吃橘子");
}
}
public class CommonTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
Fruit apple=new Apple();
apple.eat();
Fruit orange=new Orange();
orange.eat();
}
}
/*
***吃苹果
*****吃橘子*/
package org.java.factory;
interface Fruit2{
public void eat();
}
class Apple2 implements Fruit{
public void eat() {
System.out.println("***吃苹果");
}
}
class Orange2 implements Fruit{
@Override
public void eat() {
// TODO Auto-generated method stub
System.out.println("*****吃橘子");
}
}
class Factory{
/**
*
* 工厂类用于取得指定类型的接口
*/
public static Fruit getInstance(String className){
if("apple2".equals(className)){
return new Apple();
}else if("orange2".equals(className)){
return new Orange();
}else{
return null;
}
}
}
public class FactoryTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
Fruit fruit=Factory.getInstance("apple2");
fruit.eat();
}
}