没有使用工厂模式时的代码:
interface Fruit{
public void eat();
}
class Apple implements Fruit{
public void eat(){
System.out.println("**吃苹果**") ;
}
}
class Orange implements Fruit{
public void eat(){
System.out.println("**吃橘子**") ;
}
}
public class FactoryDemo01{
public static void main(String args[]){
Fruit f = new Apple();
f.eat();
}
}
/*
E:\java>javac FactoryDemo01.java
E:\java>java FactoryDemo01
**吃苹果**
*//*普通的代码编写方式*/
interface Fruit{
public void eat();
}
class Apple implements Fruit{
public void eat(){
System.out.println("**吃苹果**") ;
}
}
class Orange implements Fruit{
public void eat(){
System.out.println("**吃橘子**") ;
}
}
public class FactoryDemo01{
public static void main(String args[]){
Fruit f = new Apple();
f.eat();
}
}
/*
E:\java>javac FactoryDemo01.javaE:\java>java FactoryDemo01
**吃苹果**
*/
使用工厂模式的代码:
工厂设计模式:
在Java中主方法就类似于一个客户端,当子类发生变化时,就必须要在客户端里改变声明的对象和类。
这使得客户端和子类就紧密的耦合在一起,因此,如果在子类发生改变时,客户端也要发生相应的改变。
在程序中加入一个工厂,使得子类的声明在工厂内发生,然后再把声明后的对象返回到客户端中,
这样就避免了客户端与子类耦合的发生。
interface Fruit{
public void eat();
}
class Apple implements Fruit{
public void eat(){
System.out.println("**吃苹果**") ;
}
}
class Orange implements Fruit{
public void eat(){
System.out.println("**吃橘子**") ;
}
}
class Factory{
public static Fruit getFruit(String className){
Fruit f = null;
/*在这里使用【字符串常量的匿名对象.equals(className)】可以有效的避免出现空指向异常。*/
if ("Apple".equals(className)){
f = new Apple();
}
if ("Orange".equals(className)){
f = new Orange();
}
return f;
}
}
public class FactoryDemo02{
public static void main(String args[]){
/*直接使用工厂返回的对象。如果子类发生改变,就不再需要修改客户端。*/
Fruit f = Factory.getFruit(args[0]);
if (f!=null)
f.eat();
}
}
/*
E:\java>javac FactoryDemo02.java
E:\java>java FactoryDemo02 Apple
**吃苹果**
E:\java>java FactoryDemo02 Orange
**吃橘子**
*/