体系结构—简单工厂模式

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/LY_624/article/details/72801702

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

public interface clothingType {
	public void getType();    //打印选择的服装类型
}

public class t_shirt implements clothingType{
	@Override
	public void getType() {
		System.out.println("您选择的是T恤");  	
	}
}

public class short_sleeve implements clothingType{
	@Override
	public 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();  
	}
}

运行结果:


猜你喜欢

转载自blog.csdn.net/LY_624/article/details/72801702