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

本文介绍了工厂方法模式的概念及其应用实例,通过定义一个创建产品对象的工厂,并将实际的创建工作推迟到子类中实现。文中提供了具体的工厂类实现代码示例,并展示了如何使用该模式创建不同的水果对象。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

工厂方法模式的用意是定义一个创建产品对象的工厂,将实际的创建工作推迟到子类中。


[img]http://dl.iteye.com/upload/attachment/0073/2613/c56c357d-3bf1-36b2-b7a3-e9de19b77260.jpg[/img]

修改上节中简单工厂模式

抽象工厂

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();
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值