1 工厂模式
类实例化交给工厂,使用者只需提供类名或工厂名完成实例化。工厂模式有两种实现方式,一种是普通工厂,即工厂中实现类实例化,另一种是抽象工厂,即工厂的工厂,实际使用的工厂继承抽象工厂,抽象工厂中获取工厂接口。
2 Usage
2.1 Person接口
package basic.datatype.pattern.factory;
/**
* Person interface.
* @author xindaqi
* @since 2020-09-30
*/
public interface Person {
public void language();
}
2.2 Chinese实现
package basic.datatype.pattern.factory;
/**
* Chinese implements.
* @author xindaqi
* @since 2020-09-30
*/
public class Chinese implements Person{
@Override
public void language(){
System.out.println("====Chinese====");
}
}
2.3 English实现
package basic.datatype.pattern.factory;
/**
* English implements.
* @author xindaqi
* @since 2020-09-30
*/
public class English implements Person{
@Override
public void language(){
System.out.println("====English====");
}
}
2.4 Person工厂
package basic.datatype.pattern.factory;
/**
* Person factory.
* @author xindaqi
* @since 2020-09-30
*/
public class PersonFactory {
public Person getLanguage(String language){
if(language == null){
return null;
}
if(language.equalsIgnoreCase("Chinese")){
return new Chinese();
}else if(language.equalsIgnoreCase("English")){
return new English();
}
return null;
}
}
2.5 工厂模式
package basic.datatype.pattern.factory;
/**
* Person factory test.
* @author xindaqi
* @since 2020-09-30
*/
public class FactoryPatternTest {
public static void main(String[] args){
PersonFactory personFactory = new PersonFactory();
Person chineseLanguage = personFactory.getLanguage("chinese");
chineseLanguage.language();
Person englishLanguage = personFactory.getLanguage("english");
englishLanguage.language();
}
}
3 小结
- 工厂模式通过new实例化工厂
- 隐藏新建工厂中对象的过程
- 通过名称获取对象