简单工场(使用pulic static T create/getInstance/valueOf(){},把创建对象的细节封装起来)
工场方法(针对单一维度)
public interface IType {
}
public class YamlType implements IType {
}
public class XmlType implements IType {
}
public class PropertiesType implements IType {
}
public class JsonType implements IType {
}
public interface ITypeFactory {
IType create();
}
public class YamlTypeFactory implements ITypeFactory {
@Override
public IType create() {
return new YamlType();
}
}
public class XmlTypeFactory implements ITypeFactory {
@Override
public IType create() {
return new XmlType();
}
}
public class PropertiesTypeFactory implements ITypeFactory {
@Override
public IType create() {
return new PropertiesType();
}
}
public class JsonTypeFactory implements ITypeFactory {
@Override
public IType create() {
return new JsonType();
}
}
工场方法,创建单一维度的东西,用得比较多。要跟下面的抽象工场对比起来看。
抽象工场(针对多个维度,不常用)
public interface IType1 {
}
public class YamlType1 implements IType1 {
}
public class XmlType1 implements IType1 {
}
public class PropertiesType1 implements IType1 {
}
public class JsonType1 implements IType1 {
}
public interface IType2 {
}
public class YamlType2 implements IType2 {
}
public class XmlType2 implements IType2 {
}
public class PropertiesType2 implements IType2 {
}
public class JsonType2 implements IType2 {
}
public interface ITypeFactory {
IType1 createType1();
IType2 createType2();
}
public class YarmTypeFactory implements ITypeFactory {
@Override
public IType1 createType1() {
return new YamlType1();
}
@Override
public IType2 createType2() {
return new YamlType2();
}
}
public class XmlTypeFactory implements ITypeFactory {
@Override
public IType1 createType1() {
return new XmlType1();
}
@Override
public IType2 createType2() {
return new XmlType2();
}
}
public class PropertiesTypeFactory implements ITypeFactory {
@Override
public IType1 createType1() {
return new PropertiesType1();
}
@Override
public IType2 createType2() {
return new PropertiesType2();
}
}
public class JsonTypeFactory implements ITypeFactory {
@Override
public IType1 createType1() {
return new JsonType1();
}
@Override
public IType2 createType2() {
return new JsonType2();
}
}
抽象工场与简单工场相比,抽象工场可以创建多个维度,不过场景比较狭窄。
查看全部 浅谈模式 - 汇总篇