这篇文章将为大家详细讲解有关java中工厂模式的优缺点有哪些,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。

简单工厂模式介绍:
概要:
简单工厂模式,又称为静态工厂方法(Static Factory Method)模式,它属于类创建型模式。在简单工厂模式中,把产品的生产方法封装起来放进工厂类,工厂类可以根据参数的不同返回不同产品类的实例。工厂类就是用来生产产品的类,把生产产品的方法放到工厂类里面去,工厂类里面用switch语句控制生产哪种商品,使用者只需要调用工厂类的静态方法就可以实现产品类的实例化。
实现代码:
package scut.designmodel.SimpleFactoryPattern;
//抽象产品类
abstract class Product{
public abstract void Show();
}
//产品A类
class ProductA extends Product{
@Override
public void Show() {
System.out.println("生产出了产品A");
}
}
//产品B类
class ProductB extends Product{
@Override
public void Show() {
System.out.println("生产出了产品C");
}
}
//产品C类
class ProductC extends Product{
@Override
public void Show() {
System.out.println("生产出了产品C");
}
}
//简单工厂类
class Factory {
public static Product Manufacture(String ProductName){
switch (ProductName){
case "A":
return new ProductA();
case "B":
return new ProductB();
case "C":
return new ProductC();
default:
return null;
}
}
}
//工厂产品生产流程
public class SimpleFactoryPattern {
public static void main(String[] args){
Factory mFactory = new Factory();
//客户要产品A
try {
mFactory.Manufacture("A").Show();
}catch (NullPointerException e){
System.out.println("没有这一类产品");
}
//客户要产品B
try {
mFactory.Manufacture("B").Show();
}catch (NullPointerException e){
System.out.println("没有这一类产品");
}
//客户要产品C
try {
mFactory.Manufacture("C").Show();
}catch (NullPointerException e){
System.out.println("没有这一类产品");
}
//客户要产品D
try {
mFactory.Manufacture("D").Show();
}catch (NullPointerException e){
System.out.println("没有这一类产品");
}
}
}