一:工厂模式出现的原因
一般设计模式:
view plaincopy to clipboardprint? 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(); } } 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(); } } 在这种普通的编码方式中,后续的扩展功能将是灾难,当有新的水果类增加时,必须翻出源码进行修改,这对于一个庞大的项目来说将需要耗费巨大的人力和物力,工厂模式就是为了解决这一问题而出现的设计模式。 二,工厂设计模式 在Java中主方法就类似于一个客户端,当子类发生变化时,就必须要在客户端里改变声明的对象和类。这使得客户端和子类就紧密的耦合在一起,因此,如果在子类发生改变时,客户端也要发生相应的改在程序中加入一个工厂,使得子类的声明在工厂内发生,然后再把声明后的对象返回到客户端中这样就避免了客户端与子类耦合的发生。 三,简单工厂模式 根据提供给它的数据,返回几个可能类中的一个类的实例。通常它返回的类都有一个共同的父类和共同的方法,但每个方法执行的过程不同,而且根据不同的数据进行了优化。简单工厂模式可以作为工厂方法模式的一个引导。 public class Factory { public static Fruit factory(String canshu) { if (canshu.equals("Apple")) { return new Apple(); } else if (canshu.equals("Strawberry")) { return new Strawberry(); } else if (canshu.equals("Lichee")) { return new Lichee(); } else { return null; } } } 学习总结:工厂模式可以看做是MVC设计模式中的M层即MODEL层的具体设计方法,但工厂模式并不是就是如上所述那样简单,设计模式是设计思想的提炼,可大可小,以后将要讲的抽象工厂模式在逻辑上就比较复杂了 发表于 @ 2010年02月02日 21:52:00 | 评论( 0 ) | 编辑| 举报| 收藏
本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/chusheng2009/archive/2010/02/02/5282877.aspx
|
|