体系结构—简单工厂模式

来源:互联网 发布:贪心算法题目 编辑:程序博客网 时间:2024/05/18 15:05

编写一个简单工厂模式的程序

public interface clothingType {public void getType();    //打印选择的服装类型}public class t_shirt implements clothingType{@Overridepublic void getType() {System.out.println("您选择的是T恤");  }}public class short_sleeve implements clothingType{@Overridepublic void getType() {System.out.println("您选择的是短袖");  }}public class clothingFactory {public static clothingType CreateType(String type)      //根据提供的类型,去实例化具体的对象      {  clothingType ctype = null;          switch (type)        {               case"T恤":                  ctype = new t_shirt();  //如果是T恤,则返回T恤子类                  break;              case"短袖":                  ctype = new short_sleeve();  //如果是短袖,则返回短袖子类                  break;          }          return ctype;      }  }   public class 服装厂 {public static void main(String[] args) {clothingType type1 = clothingFactory.CreateType("T恤");           //传入参数“T恤”,让工厂去实例化对象的T恤类          type1.getType();          clothingType type2 = clothingFactory.CreateType("短袖");         //传入参数“短袖”,让工厂去实例化对象的短袖类         type2.getType();  }}

运行结果:


原创粉丝点击