| |
//package com.cc; import java.util.*; import java.lang.class; interface book{ void saybookname(); void saybookprice(); } class chinesebook implements book //中文书 { private string name; private int price; public chinesebook(){ //this.chinesebook("chinese",10); name = "chinesebook"; price = 10; } public chinesebook(string name,int price){ this.name = name; this.price = price; } public void saybookname(){ system.out.println("i am a chinese book "+name); } public void saybookprice(){ system.out.println("my price is "+price); } //继承书店工厂 // private static class factory extends bookfactory //内部类的使用 { protected book create(){ return new chinesebook(); } } static { //生成1个实例后,就要把这个实例加到工厂中 system.out.println("loading chinesebook.class"); bookfactory.addfactory("chinesebook",new factory()); //为什么要把工厂 //放到list中呢?便于加载一次以后可直接调用 } } class englishbook implements book //英文书 { private string name; private int price; public englishbook(){ //this.englishbook("english",10); name = "englisthbook"; price = 10; } public englishbook(string name,int price){ this.name = name; this.price = price; } public void saybookname(){ system.out.println("i am a english book "+name); } public void saybookprice(){ system.out.println("my price is "+price); } //继承书店工厂 // private static class factory extends bookfactory { protected book create(){ return new englishbook(); } } static { //生成1个实例后,就要把这个实例加到工厂中 system.out.println("loading englishbook.class"); bookfactory.addfactory("englishbook",new factory()); //为什么要把工厂 //放到list中呢?便于加载一次以后可直接调用 } } abstract class bookfactory { protected abstract book create(); //这个方法要在具体类中实现 private static map factories = new hashmap(); //工厂map public static void addfactory(string id,bookfactory f) { //加入工厂,将书和创建书的工厂加入到map中,为什么要加入创建书的工厂呢? //因为创建书的工厂有个create()方法,他要具体返回一个实例 system.out.println(factories.put(id,f)); } public static final book createbook(string id){//创建书实例,书的名称作为参数,传出的是被创建好的book的实例 if (!factories.containskey(id))//当工厂中不包含这个类时要装载 { try{ // load dynamically 动态装载 class.forname(id); //怎么加载的?只要直接执行 //这个类,类就会调用static里的语句 }catch(classnotfoundexception e){ throw new runtimeexception("error"+id); } // see if it was put in 看看它是否被装载 if(!factories.containskey(id))throw new runtimeexception("bad shape creation: " + id); } return ((bookfactory)factories.get(id)).create(); } } public class bookfactory2 { string booklist[] = {"englishbook", "chinesebook","englishbook","chinesebook","chinesebook","englishbook"}; list books = new arraylist(); public void test(){ for (int i=0;i<booklist.length;i++) { books.add(bookfactory.createbook(booklist)); system.out.println("already create"); } iterator it = books.iterator(); while(it.hasnext()){ book s = (book)it.next(); s.saybookname(); } } public static void main(string args[]) { new bookfactory2().test(); } }
|
|