/** * 书 */ public abstract class Book { /** * 打印书籍名字 */ public abstract void printName(); }
/** * 英语书 */ public class EnglishBook extends Book { @Override public void printName() { System.out.println("this is 《English Book》"); } }
/** * Java编程 */ public class JavaBook extends Book { @Override public void printName() { System.out.println("this is 《Java Book》"); } }
public interface BookFactory { /** * 生产书籍 * @return 书籍 */ Book createBook(); }
/** * EnglishBook工厂 */ public class EnglishBookFactory implements BookFactory { @Override public Book createBook() { return new EnglishBook(); } }
/** * JavaBook工厂 */ public class JavaBookFactory implements BookFactory { @Override public Book createBook() { return new JavaBook(); } }
public class Client { public static void main(String[] args) { Book book = new EnglishBookFactory().createBook(); book.printName(); book = new JavaBookFactory().createBook(); book.printName(); } }
输出
this is 《English Book》 this is 《Java Book》