栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

JAVA设计模式-工厂模式

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

JAVA设计模式-工厂模式

工厂模式 工厂方法模式
//接口
interface Product1
{
    void method1();
}

//继承实现
class Product1A implements Product
{
    @Override
    public void method1() {
        System.out.println("ProductA---method1");
    }
}

//继承实现
class Product1B implements Product
{
    @Override
    public void method1() {
        System.out.println("ProductB---method1");
    }
}

//调用方式
public class FactoryMethod
{
    public static void main(String[] args) {
        Product product = new Product1A();
        product.method1();
    }
}
简单工厂模式
//接口
interface Product
{
    void method1();
}

//继承实现A
class ProductA implements Product
{
    @Override
    public void method1() {
        System.out.println("ProductA.method1 executed.");
    }
}

//继承实现B
class ProductB implements Product
{
    @Override
    public void method1() {
        System.out.println("ProductB.method1 executed.");
    }
}

// 简单工厂
class SimpleFactoryIn
{
    public static Product createProduct(String type) {
        if ("A".equals(type)) {
            return new ProductA();
        }
        else if ("B".equals(type)) {
            return new ProductB();
        }
        return null;
    }
}


public class SimpleFactory
{
    public static void main(String[] args) {
        Product product = SimpleFactoryIn.createProduct("A");
        product.method1();
    }
}
工厂模式-支持闭包拓展
@Component
public class DynamicFactory
{

    private static Map dyFactory = new HashMap<>();

    
    public static void register(String type, ProductInter productInter) {
        if (type != null) {
            dyFactory.put(type, productInter);
        }
    }

    public static ProductInter getProduct(String type) {
        return dyFactory.get(type);
    }
}

//接口
public interface ProductInter
{
    void method1();
}

//继承实现
@Service
public class ProductImplA implements ProductInter
{

    //启动时加入到工程中
    @PostConstruct
    private void init() {
        DynamicFactory.register("productimpla", new ProductImplA());
    }

    @Override
    public void method1() {
        System.out.println("ProductA.method1 executed.");
    }
}

//继承实现
@Service
public class ProductImplB implements ProductInter
{
    @PostConstruct
    private void init() {
        DynamicFactory.register("productimplb", new ProductImplB());
    }

    @Override
    public void method1() {
        System.out.println("ProductB.method1 executed.");
    }
}

//测试
   @Test
    void test() {
    //传入对应的初始化名称
        ProductInter product = DynamicFactory.getProduct("productimpla");
        product.method1();
    }
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/842983.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号