易学设计模式八 工厂方法(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();
	}
}

猜你喜欢

转载自jiaozhiguang-126-com.iteye.com/blog/1670721
今日推荐