package com.swt.dp.factory; /** * 书 */ public abstract class Book { /** * 打印书籍名字 */ public abstract void printName(); }
package com.swt.dp.factory; /** * 英语书 */ public class EnglishBook extends Book { @Override public void printName() { System.out.println("this is 《English Book》"); } }
package com.swt.dp.factory; /** * Java编程 */ public class JavaBook extends Book { @Override public void printName() { System.out.println("this is 《Java Book》"); } }
package com.swt.dp.factory; /** * 数学书 */ public class MathematicsBook extends Book { @Override public void printName() { System.out.println("this is 《Mathematics Book》"); } }
package com.swt.dp.factory; /** * 简单工厂模式 */ public class BookFactory { /** * 生产书籍 * @param name 书籍名字 * @return 书籍 */ public static Book creatBook(String name) { switch (name) { case "English" : { return new EnglishBook(); } case "Java" : { return new JavaBook(); } case "Mathematics" : { return new MathematicsBook(); } default:{ break; } } return null; } }
package com.swt.dp.factory; public class Client { public static void main(String[] args) { Book book = BookFactory.creatBook("English"); book.printName(); book = BookFactory.creatBook("Java"); book.printName(); book = BookFactory.creatBook("Mathematics"); book.printName(); } }
打印
this is 《English Book》 this is 《Java Book》 this is 《Mathematics Book》