其他分享
首页 > 其他分享> > 工厂模式(一)简单工厂模式

工厂模式(一)简单工厂模式

作者:互联网

用生产螺丝的例子,比如生产6号螺丝和8号螺丝;当另外再生产7号螺丝的时候,只需要新建一个类,实现Screw即可,同时修改工厂类。

public interface Screw {
	public void create();
}
public class SixScrew implements Screw{
	@Override
	public void create() {
		System.out.println("生产6号螺丝。");;
	}
}
public class EgihtScrew implements Screw{
	@Override
	public void create() {
		System.out.println("生产8号螺丝。");
	}
}
public class ScrewFactory {

	public static Screw createScrew(String type){
		
		Screw screw = null;
		switch (type) {
		case "1":
			screw = new SixScrew();
			break;
		case "2":
			screw = new EgihtScrew();
			break;
		case "3":
			screw = new SevenScrew();
			break;
		default:
			break;
		}
		return screw;
	}
}
public class Store {

	public static void main(String[] args) {
		
		Screw screw = ScrewFactory.createScrew("1");
		screw.create();
		System.out.println("=======================");
		Screw screw1 = ScrewFactory.createScrew("2");
		screw1.create();
		System.out.println("=======================");
		Screw screw2 = ScrewFactory.createScrew("3");
		screw2.create();
	}
}
public class SevenScrew implements Screw{
	@Override
	public void create() {
		System.out.println("生产7号螺丝。");
	}
}

标签:Screw,screw,create,System,模式,工厂,螺丝,简单,public
来源: https://www.cnblogs.com/kaka-qiqi/p/14843855.html