设计模式--简单工厂模式

简单工厂模式:

普通工厂模式:
就是建立一个工厂类,对实现了同一接口的一些类进行实例的创建.

多个工厂方法模式:
是对普通工厂方法模式的改进,在普通工厂方法模式中,如果传递的字符串出错,则不能正确创建对象,而多个工厂方法模式是提供多个工厂方法,分别创建对象.

首先定义一个接口:
/*
*

  • @author DCH

*/

public interface Work {

//提供服务
public void service();

}

定义两个类来实现这个接口:

第一个Computer类:
/*
*

  • @author DCH

*/
public class Computer implements Work {

public void service(){
	System.out.println("电脑可以用来办公");
}

}

第二个Mobile类
/*
*

  • @author dch

*/

public class Mobile implements Work {

public void service(){
	System.out.println("手机可以用来办公");
}

}

简单工厂类:SimpleFactory
/*
*

  • @author dch

*/

public class SimpleFactory {

static SimpleFactory factory=null;
//1.私有构造器
private SimpleFactory(){
	
}
//2.提供一个返回该类的方法
public static SimpleFactory getSimpleFactory(){
	if(factory==null){
		factory = new SimpleFactory();
	}
	return factory;
}
/*
 * 
 * 工厂的实例方法,可以创建不同的对象
 * 
 */


public Work getObject(String type){
	if("mobile"==type){
		return new Mobile();
	}else if("computer"==type){
		return new Computer();
	}else{
		System.out.println("不能被创建");
		return null;
	}
}


//多个工厂方法模式
public Work getMoblie(){
	 return new Mobile();
}

public Work getComputer(){
	 return new Computer();
}

猜你喜欢

转载自blog.csdn.net/qq_41035395/article/details/88558151