学习研磨设计模式之简单工厂
看了 研磨设计模式之简单工厂后 觉得写的很好 自己写个加深印象 以后会继续学习作为一个顾客,我最想的就是,我只想买东西,但是具体的买什么东西,交给哪个售货员 去买,我不想管,这样最方便。那就用这个做为例子吧。
我到一个统一的售货员处(interface Seller),告诉她我需要什么东西(param),她会自己指派哪个售货员(Seller的实现类)来来买东西给我。
接口
public interface Seller {public void sell();}
Food实现类
//Seller 接口的实现类2public class FoodSeller implements Seller { private String foodname=null; public void sell() {System.out.println("you've got food : "+foodname);}public FoodSeller(String foodname){this.foodname=foodname;}}
Cloth实现类
//Seller 接口的实现类1public class ClothSeller implements Seller {private String clothname=null; public ClothSeller( String clothname){this.clothname=clothname; }public void sell() {System.out.println("you've got cloth : "+clothname);}}
工厂类
public class MyFactory { //简单的工厂类/** *@param type *@return */public static Seller sellBread(String type){Seller seller=null;if(type.equals("food")){seller=new FoodSeller("food");}else if(type.equals("cloth")){seller=new ClothSeller("cloth");}return seller;}}
顾客类
public class Client {/** * @param args */public static void main(String[] args) {Seller seller=MyFactory.sellBread("food");if(null!=seller){seller.sell();System.out.println("客户正在利用简单工厂来购买商品!");}else {System.out.println("没有找到您要找的商品!");}}}
页:
[1]