首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 软件管理 > 软件开发 >

易学设计形式八 工厂方法(Factory Method)

2012-11-13 
易学设计模式八 工厂方法(Factory Method)工厂方法模式的用意是定义一个创建产品对象的工厂,将实际的创建

易学设计模式八 工厂方法(Factory Method)
工厂方法模式的用意是定义一个创建产品对象的工厂,将实际的创建工作推迟到子类中。




修改上节中简单工厂模式

抽象工厂

public interface FruitGardener {public Fruit factory();}

具体工厂
public class AppleGardener implements FruitGardener {public Fruit factory() {return new Apple();}}


public class GrapeGardener implements FruitGardener {public Fruit factory() {return new Grape();}}


public class StrawberryGardener implements FruitGardener {public Fruit factory() {return new Strawberry();}}


其他类请参照,上一篇博客,简单工厂模式

测试类
public class Client {public static void main(String[] args) {FruitGardener ag = new AppleGardener();Fruit apple = ag.factory();apple.plant();apple.grow();apple.harvest();FruitGardener gg = new GrapeGardener();Fruit grape = gg.factory();grape.plant();}}


输出结果:

Apple has been planted
Apple is growing
Apple has been havested
Grape has been planted


URL 与 URLConnection的应用
URL hao360 = new URL("http://hao.360.cn/");
URLConnection hc = hao360.openConnection();
URLConnection是一个抽象类,所以hao360.openConnection()返回的一定是URLConnection的子类,所以openConnection()是工厂方法。
public class URLConnectionReader {public static void main(String[] args) throws Exception {URL hao360 = new URL("http://hao.360.cn/");URLConnection hc = hao360.openConnection();BufferedReader in = new BufferedReader(new InputStreamReader(hc.getInputStream()));String inputLine;while((inputLine = in.readLine()) != null) {System.out.println(inputLine);}in.close();}}

热点排行