简单工厂模式

来源:互联网 发布:淘宝做任务赚钱 编辑:程序博客网 时间:2024/06/05 04:28

去麦当劳吃东西,麦当劳为工厂,提供milk和mcchichen食物。
public interface Food {public void getFood();}
mcchicken代码
package simplefactory;public class McChicken implements Food {public void getFood() {<span style="white-space:pre"></span>System.out.println("Get a Chicken!");<span style="white-space:pre"></span>}}
Milk:
package simplefactory;public class Milk implements Food {public void getFood() {<span style="white-space:pre"></span>System.out.println("Get Milk!");<span style="white-space:pre"></span>}}
工厂麦当劳
package simplefactory;public class McDlz {<span style="white-space:pre"></span>public static Food getFood(String type) throws<span style="white-space:pre"></span>InstantiationException,IllegalAccessException,ClassNotFoundException{<span style="white-space:pre"></span>if(type.equalsIgnoreCase("mcchicken")){<span style="white-space:pre"></span>return (Food)McChicken.class.newInstance();<span style="white-space:pre"></span>}else if(type.equalsIgnoreCase("milk")){<span style="white-space:pre"></span>return (Food)Milk.class.newInstance();<span style="white-space:pre"></span>}else{<span style="white-space:pre"></span>System.out.println("Can't find this food!");<span style="white-space:pre"></span>return null;<span style="white-space:pre"></span>}<span style="white-space:pre"></span>}}
测试客户端:
package simplefactory;public class SimpleFactory {<span style="white-space:pre"></span>/**<span style="white-space:pre"></span> * @param args<span style="white-space:pre"></span> * @throws ClassNotFoundException <span style="white-space:pre"></span> * @throws IllegalAccessException <span style="white-space:pre"></span> * @throws InstantiationException <span style="white-space:pre"></span>*/<span style="white-space:pre"></span>public static void main(String[] args) throws InstantiationException, IllegalAccessException, ClassNotFoundException {<span style="white-space:pre"></span>Food mcChicken = McDlz.getFood("mcchicken");<span style="white-space:pre"></span>Food milk = McDlz.getFood("milk");<span style="white-space:pre"></span><span style="white-space:pre"></span>if(mcChicken != null){<span style="white-space:pre"></span>mcChicken.getFood();<span style="white-space:pre"></span>}<span style="white-space:pre"></span>if(milk != null){<span style="white-space:pre"></span>milk.getFood();<span style="white-space:pre"></span>}<span style="white-space:pre"></span>}}

0 0
原创粉丝点击