JAVA设计模式(1)创建型-工厂方法

本文介绍了工厂方法模式的应用,通过创建多个工厂类来独立生产ProductA、ProductB和ProductC产品,每个工厂负责生成相应的产品实例。在客户端代码中,通过切换工厂类实现了动态创建不同类型产品的能力。
摘要由CSDN通过智能技术生成

工厂方法模式:每个工厂独立生产产品

产品接口

package factory;
/**
 *
 * @author V: jbossjf
 *
 */
public interface Product {
    //声明类所需继承的共同接口,也可以是抽象类
}

 产品类

package factoryMehtod;
/**
 *
 * @author V:  jbossjf
 *
 */

public class ProductA implements Product {
    public ProductC() {
        System.out.println("productA");
    }
}

package factoryMehtod;
/**
 *
 * @author V:  jbossjf
 *
 */

public class ProductB implements Product {
    public ProductC() {
        System.out.println("productB");
    }
}


package factoryMehtod;
/**
 *
 * @author V:  jbossjf
 *
 */

public class ProductC implements Product {
    public ProductC() {
        System.out.println("productC");
    }
}

产品工厂接口

package factoryMehtod;
/**
 *
 * @author jbossjf
 *
 */
public interface Factory {
    //声明产生产品类的方法
    public Product createProduct();
}

产品工厂

package factoryMehtod;
/**
 *
 * @author V:  jbossjf
 *
 */
public class FactoryA implements Factory {
    //实现工厂类的方法生成产品类A
    public Product createProduct()
    {
        return new ProductA();
    }

}

package factoryMehtod;
/**
 *
 * @author V:  jbossjf
 *
 */
public class FactoryB implements Factory {
    //实现工厂类的方法生成产品类B
    public Product createProduct()
    {
        return new ProductB();
    }

}


package factoryMehtod;
/**
 *
 * @author V:  jbossjf
 *
 */
public class FactoryC implements Factory {
    //实现工厂类的方法生成产品类C
    public Product createProduct()
    {
        return new ProductC();
    }

}

调用

package factoryMehtod;
/**
 *
 * @author V: jbossjf
 *
 */
public class Client {
    public static void main(String[] args) {
        Factory factory;
        factory = new FactoryA();
        factory.createProduct();
        factory = new FactoryB();
        factory.createProduct();
        factory = new FactoryC();
        factory.createProduct();
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值