上一节的模版方法是在父类建立处理逻辑的大纲骨架,而在子类补充具体的处理内容,如果把这个Pattern应用在产生对象实例方面,就是本节的学习重点,工厂模式。
这个程序示例主要是建立一个生产身份证的工厂。
程序包 |
名称 |
说明 |
framework |
Product |
仅定义抽象方法use的抽象类 |
framework |
Factory |
实现方法create的抽象类 |
idcard |
IDCard |
实现方法use的抽象类 |
idcard |
IDCardFactory |
实现方法createProduct,egisterProduct的类 |
|
Main |
测试类 |
Product抽象类
- package framework;
- public abstract class Product {
- public abstract void use();
- }
- }
Factory 抽象类
- package framwork ;
- public abstract class Factory {
- public final Product create(String owner) {
- Product p = createProduct(owner);
- registerProduct(p);
- return p;
- }
- protected abstract Product createProduct(String owner);
- protected abstract void registerProduct(Product product);
- }
IDCard 子类
- package idcard;
- import framework.*;
- public class IDCard extends Product {
- private String owner;
- IDCard(String owner) {
- System.out.println("建立"+owner+"的卡。");
- this.owner = owner ;
- }
- public void use () {
- System.out.println("使用"+owner + " 的卡。");
- }
- public String getOwner() {
- return owner;
- }
- }
IDCardFactory 子类
- package idcard;
- import frameWork.*;
- import java.util.*;
- public class IDCardFactory extrends Factory {
- private Vector owners = new Vector();
- protected Product createrProduct (String owner) {
- return new IDCard(owner);
- }
- protected void registerProduct(Product product) {
- owners.add(((IDCard)product).getOwner());
- }
- public Vector getOwner() {
- return owners;
- }
- }
Main测试类
- import framwork.*;
- import idcard.*;
- public class Main {
- public static void main(String args[]) {
- Factory factory = new IDCardFactory();
- Product card1 = factory.create("qingzi2534");
- Product card2 = factory.create("javaeye");
- card1.use();
- card2.use();
- }
- }