设计模式--工厂方法模式

工厂方法模式

概念

工厂方法模式(FACTORY METHOD)是一种常用的类创建型设计模式,此模式的核心精神是封装类中变化的部分,提取其中个性化善变的部分为独立类,通过依赖注入以达到解耦、复用和方便后期维护拓展的目的。它的核心结构有四个角色,分别是抽象工厂;具体工厂;抽象产品;具体产品

设计类图

工厂方法模式类图为了克服简单工厂方法模式的缺点(简单工厂方法模式不符合开闭原则的原因是工厂方法类是一个实体类,每当有一个新的产品类被加入到产品类的结构中时,在工厂方法类中必须增加适当的条件语句),人们提出工厂方法模式。工厂方法模式首先需要一个接口作为超类,名为creator,接口中有一个方法,叫做factory();然后可以用和产品类相同的结构产生创建者类的结构,其中包含CreatorA 和CreatorB,各自负者创建相应的ProductA 和ProductB 的对象。

介绍

1. 简单工厂方法模式和工厂方法模式的区别

  • 两个模式的中心不同。工厂方法模式的中心是抽象工厂类或者接口,而简单工厂方法模式的中心是一个实的工厂类(Concrete Factory Class)。
  • 简单工厂方法模式不支持开闭原则,工厂方法模式支持开闭原则。
  • 在简单工厂模式中,必要的创建对象的逻辑判断包含在工厂类中;在工厂方法模式中,工厂类不必要包含创建对象的逻辑判断。
  • 简单工厂模式是静态的,而工厂模式是动态的。

2. 可以使用工厂方法模式的情况

  • 创建某些类的对象逻辑比较复杂,并且有很多条件分支,而且还可能增减新的条件。
  • 一个类不能预先准确的知道它必须创建一个层次类中哪个子类对象。
  • 一个类使用它的子类决定所要创建的对象。
  • 需要封装创建类的对象的逻辑,使得这些逻辑局部化。

3. 优缺点

  • 优点
  1. 工厂方法模式将创建对象的逻辑与任务交给了工厂类
  2. 工厂方法模式支持开闭原则

应用场景

:假如要设计一个汽车保险管理程序。汽车保险分为许多险种,例如人身伤亡(Body Injury)、碰撞(Collision)、驾驶员本身伤亡(Person Injury)、财产损失(Property)、综合险(Com)等。如果一个应用指导它所需的准确功能,它可以从客户类的主方法中直接初始化类结构体中的某个子类,并且调用该类提供的功能。

1. 类设计图
类设计图2. 有关的代码
以下为用户界面的代码:

public class FactoryMethodGUI extends JFrame
{
  private JSplitPane  bigSplitPane;
  private JScrollPane showInfoPane;
  private JPanel btnPanel;
  private JComboBox cmbInsuranceType, cmbHouseType;
  private JLabel lblInsureType;
  private Dimension   minimumSize;
  private JTextArea txtForInfo;

  public static final String SHOW = "Show Info";
  public static final String EXIT = "Exit";
  public static final String BODYINJURE = "Body Injur Liability";
  public static final String COLLISION = "Collision Coverage";
  public static final String PERSONINJURE = "Personal Injury Protection";
  public static final String PROPERTY = "Property Damage Liability";
  public static final String COMPREHENSIVE = "Comprehensive Coverage";
  public static final String DANGEROUS = "Dangerous Everywhere";

  public FactoryMethodGUI() {
     super("Factory Method Pattern- Auto Insurance. ");
     minimumSize = new Dimension(130, 100);
     setUpChoicePanel();
     setUpScrollPanes();
   }

  private void setUpChoicePanel() {

      cmbInsuranceType = new JComboBox();
	  cmbInsuranceType.addItem(BODYINJURE);
	  cmbInsuranceType.addItem(COLLISION);
	  cmbInsuranceType.addItem(PERSONINJURE);
	  cmbInsuranceType.addItem(PROPERTY);
	  cmbInsuranceType.addItem(COMPREHENSIVE);
	  cmbInsuranceType.addItem(DANGEROUS);
	  
	  lblInsureType = new JLabel("Insurance Types");

	  //Create the open button
	  JButton openButton = new JButton(SHOW);
	  openButton.setMnemonic(KeyEvent.VK_S);
	  JButton exitButton = new JButton(EXIT);
	  exitButton.setMnemonic(KeyEvent.VK_X);

	  ButtonListener btnListener = new ButtonListener();

	  // add action Listener
	  openButton.addActionListener(btnListener);
	  exitButton.addActionListener(btnListener);

	  btnPanel = new JPanel();

	  //------------------------------------------------
	  GridBagLayout gridbag = new GridBagLayout();
	  btnPanel.setLayout(gridbag);
	  GridBagConstraints gbc = new GridBagConstraints();

	  btnPanel.add(lblInsureType);
	  btnPanel.add(cmbInsuranceType);
	  btnPanel.add(openButton);
	  btnPanel.add(exitButton);

      gbc.insets.top = 5;
      gbc.insets.bottom = 5;
      gbc.insets.left = 5;
      gbc.insets.right = 5;

      gbc.gridx = 0;
      gbc.gridy = 0;
      gridbag.setConstraints(lblInsureType, gbc);
      gbc.gridx = 1;
      gbc.gridy = 0;
      gridbag.setConstraints(cmbInsuranceType, gbc);

      gbc.insets.left = 2;
      gbc.insets.right = 2;
      gbc.insets.top = 15;
      gbc.gridx = 0;
      gbc.gridy = 5;
      gridbag.setConstraints(openButton, gbc);
      gbc.anchor = GridBagConstraints.WEST;
      gbc.gridx = 1;
      gbc.gridy = 5;
      gridbag.setConstraints(exitButton, gbc);
      //-----------------------------------------------
   }

   private void setUpScrollPanes() {
   	  Border raisedbevel = BorderFactory.createRaisedBevelBorder();

   	  txtForInfo = new JTextArea("Auto insurance information will be shown here.", 15, 20);
   	  txtForInfo.setFont(new Font("Helvetica", Font.BOLD, 15));

  	  txtForInfo.setLineWrap(true);
  	  txtForInfo.setBackground(Color.pink);

  	  showInfoPane = new JScrollPane(txtForInfo);

  	  bigSplitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, showInfoPane, btnPanel);
  	  bigSplitPane.setDividerLocation(160);

      getContentPane().add(bigSplitPane);
  	  //setSize(new Dimension(500, 300));
  	  //setSize(new Dimension(500, 300));
      setVisible(true);
   }

   class ButtonListener implements ActionListener {
      public void actionPerformed(ActionEvent ae) {

		if (ae.getActionCommand().equals(EXIT)) {
		    System.exit(1);
		}

		if (ae.getActionCommand().equals(SHOW)) {

		    String type = (String) cmbInsuranceType.getSelectedItem();
		    PolicyProducer pp=null;

		    if (type.equals(BODYINJURE)) {
				pp= new BodyInjurPolicyProducer();
		    }
		    if (type.equals(COLLISION)) {
		        pp= new CollisionPolicyProducer();
		    }
		    if (type.equals(PERSONINJURE)) {
				pp= new PersonInjuryPolicyProducer();
		    }
		    if (type.equals(PROPERTY)) {
				pp= new PropertyDamagePolicyProducer();
			 }
			 if (type.equals(COMPREHENSIVE)) {
				pp= new ComprehensivePolicyProducer();
		     }
			 if (type.equals(DANGEROUS)) {
					pp= new DangerousPolicyProducer();
			     }

		     AutoInsurance ai = pp.getPolicyObj();
			 String desc = ai.getInsuranceDescription();
			 txtForInfo.setText(desc);
          }
      }
   }

   public static void main(String args[])
   {
      try {
         UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
      }
      catch (Exception evt) {}

      FactoryMethodGUI frame = new FactoryMethodGUI();
      frame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent e)
         {
            System.exit(0);
         }
      }
      );
     // frame.setSize(500, 420);
       frame.setSize(500, 300);
      frame.setVisible(true);
   }
}

以下为产品类接口及其实现类:

/*产品类接口*/
public interface AutoInsurance {
	abstract String getInsuranceDescription();
}

/*实现类*/
public class BodyInjurLiability implements AutoInsurance {
	private String description;

	public String getInsuranceDescription() {
		description = " Body Injur Liability: \n\nBodily injury coverage pays for medical bills"
				+ " lost wages, rehabilitation, treatment and/or" + " funeral costs for anyone injured or killed "
				+ " by your car. Such coverage will also pay for" + " pain and suffering damages when a third "
				+ " party successfully sues. ";
		return description;
	}
}

public class CollisionCoverage implements AutoInsurance {
	private String description;

	public String getInsuranceDescription() {
		description = "Collision Coverage: \n\nPays for damage to your car, less"
				+ "any deductible, no matter who is at" + "fault. If your car is financed, your"
				+ "lender may require you to buy this coverage"
				+ "and may even require a particular deductible amount.";
		return description;
	}
}

public class ComprehensiveCoverage implements AutoInsurance {
	private String description;

	public String getInsuranceDescription() {
		description = "Comprehensive Coverage: \n\nPays for damage to or loss of your"
				+ "car in the event of fire, theft or" + "vandalism. Again, your lender may"
				+ "require this coverage if your car is financed.";
		return description;
	}
}

public class DangerousLiability implements AutoInsurance {
	private String description;

	public String getInsuranceDescription() {
		description = " Dangerous Liability: \n\nDangerous is EveryWhere"
				+ " you should be careful for youself everywhere ";
		/*
		 * " funeral costs for anyone injured or killed " +
		 * " by your car. Such coverage will also pay for" +
		 * " pain and suffering damages when a third " + " party successfully sues. ";
		 */
		return description;
	}
}

public class PersonalInjuryProtection implements AutoInsurance {
	private String description;

	public String getInsuranceDescription() {
		description = "Personal Injury Protection \n\nPays medical expenses and some percentage"
				+ "of lost wages to you or anyone authorized" + "to drive your car, no matter who caused the accident.";
		return description;
	}
}

public class PropertyDamageLiability implements AutoInsurance {
	private String description;

	public String getInsuranceDescription() {
		description = "Property Damage Liability: \n\nThis coverage pays for the repair and"
				+ "replacement of vehicles and other " + "property damaged when you or another"
				+ "authorized driver causes an accident.";
		return description;
	}
}
	

以下为工厂类接口及其实现类:

/*工厂类接口*/
public interface PolicyProducer {
	public AutoInsurance getPolicyObj();
}

/*实现类*/
public class BodyInjurPolicyProducer implements PolicyProducer
{
	public AutoInsurance getPolicyObj() //Fruit factory()
    {
        return new BodyInjurLiability();
    }
}

public class CollisionPolicyProducer implements PolicyProducer
{
    public AutoInsurance getPolicyObj() //Fruit factory()
    {
        return new CollisionCoverage();
    }
}

public class ComprehensivePolicyProducer implements PolicyProducer
{
    public AutoInsurance getPolicyObj() //Fruit factory()
    {
        return new ComprehensiveCoverage();
    }
}

public class DangerousPolicyProducer implements PolicyProducer 
{
	public AutoInsurance getPolicyObj() {
		return new DangerousLiability();
	}
}

public class PersonInjuryPolicyProducer implements PolicyProducer
{
    public AutoInsurance getPolicyObj() //Fruit factory()
    {
        return new PersonalInjuryProtection();
    }
}

public class PropertyDamagePolicyProducer implements PolicyProducer
{
    public AutoInsurance getPolicyObj() //Fruit factory()
    {
        return new PropertyDamageLiability();
    }
}

3. 运行结果
用户图形界面:
在这里插入图片描述在这里插入图片描述

上篇:软件设计模式例子代码  【例2.2】简单工厂方法模式-汽车保险  【例2.3】工厂方法模式-汽车保险  【例2.4】抽象工厂模式-房屋信息  【例2.5】生成器模式-房屋信息  【例2.6】单例模式-互联网连接  【例3.2】组合模式-五子棋代码  【例3.3】组合模式-空军指挥系统  【例3.4】组合模式-世界问候语  【例3.7】类适配器模式-客户信息验证  【例3.8】对象适配器模式-字符串排序  【例3.10】外观模式-安全系统  【例3.11】外观模式-椭圆功能  【例3.13】桥接模式-茶水机系统  【例3.14】桥接模式-几何立体体积  【例4.1】迭代器模式-矩阵搜索  【例4.2】迭代器模式-产品搜索  【例4.4】访问者模式-名牌鞋销售软件  【例4.5】访问者模式-计算机部件销售软件  【例4.6】命令模式-室内温度控制  【例4.7】命令模式-室内温度控制-2个GUI  【例4.8】命令模式-室内温度控制-3个GUI  【例4.10】中介者模式-旅游信息共享  【例4.11】中介者模式-海岛机场  【例4.13】策略模式-整数排序  【例4.14】策略模式-中国属相  【例4.16】状态模式-交通信号灯-设计1  【例4.16】状态模式-交通灯信号灯-设计2  【例4.16】状态模式-交通灯信号灯-设计3 下篇:软件体系结构例子代码  【例6.4】结构化设计-文件更新-C源代码  【例6.5】面向对象设计架构-文件更新  【例6.7】顺序批处理架构-文件更新  【例6.8】顺序批处理架构-图像处理  【例6.9】管道过滤器架构-主动过滤器  【例6.10】管道过滤器架构-被动过滤器  【例6.11】管道-过滤器架构-文件更新  【例6.12】管道-过滤器架构-图像处理程  【例6.14】事件体系结构-鼠标响应  【例6.17】事件体系结构-观察者模式-大草原1  【例6.18】事件体系结构-观察者模式-大草原2  【例6.19】事件体系结构-观察者模式-温度显示  【例6.21】层次架构-软件测试  【例6.22】层次架构-银行- Access数据库  【例6.23】MVC架构-二手车拍卖-无观察者  【例6.24】MVC架构-二手车拍卖-观察者-3个图形界面  【例6.25】MVC架构-二手车拍卖-观察者-1个图形界面
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值