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

工厂方法模式

概念

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

设计类图

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

介绍

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

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

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

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

3. 优缺点

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

应用场景

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

1. 类设计图
设计模式--工厂方法模式_第2张图片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. 运行结果
用户图形界面:
设计模式--工厂方法模式_第3张图片设计模式--工厂方法模式_第4张图片

你可能感兴趣的:(软件设计模式和体系结构)