简介
工厂模式属于创造型模式,它提供了一种创建对象的最佳方式。
创建对象时,无需指定创建的具体类。
它在创建时提供了一种封装机制,将实际创建的代码与使用代码分离。
主要用于解决接口选择问题;通过让其子类实现工厂,返回的也是一个抽象的对象。
具体实现
1、创建一个接口
public interface Number {
void count();
}
2、创建实现接口的实体类
One.java
public class One implements Number{
@Override
public void count() {
System.out.println("这是One实现的Number中的count方法");
}
}
Two.java
public class Two implements Number{
@Override
public void count() {
System.out.println("这是Two实现的Number中的count方法");
}
}
Three.java
public class Three implements Number{
@Override
public void count() {
System.out.println("这是Three实现的Number中的count方法");
}
}
3、创建一个工厂,生成基于给定信息的实体类的对象
/**
* 这是一个数字工厂类
*/
public class NumberFactory {
/**
* 使用getNumber获取方法的具体实现
* @return
*/
public Number gerNumber(String numberType){
if(numberType == null){
return null;
}
if("One".equals(numberType)){
return new One();
}else if("Two".equals(numberType)){
return new Two();
}else if ("Three".equals(numberType)){
return new Three();
}
return null;
}
}
4、使用工厂,通过传递类型信息来获取实体类的对象
public class Test {
public static void main(String[] args) {
NumberFactory numberFactory = new NumberFactory();
// 获取One对象,并调用他的count方法
Number one = numberFactory.gerNumber("One");
one.count();
// 获取Two对象,并调用他的count方法
Number two = numberFactory.gerNumber("Two");
two.count();
// 获取Three对象,并调用他的count方法
Number three = numberFactory.gerNumber("Three");
three.count();
}
}
输出结果
这是One实现的Number中的count方法
这是Two实现的Number中的count方法
这是Three实现的Number中的count方法