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

2021/6/3 10:26:00

本文主要是介绍工厂模式(一)简单工厂模式,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

用生产螺丝的例子,比如生产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号螺丝。");
	}
}


这篇关于工厂模式(一)简单工厂模式的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程