浅谈模式 - 工场模式

简单工场(使用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();
    }
}

抽象工场与简单工场相比,抽象工场可以创建多个维度,不过场景比较狭窄。

查看全部 浅谈模式 - 汇总篇

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值