我学过的工厂模式总共有三种,分别是简单工厂模式、工厂模式和抽象工厂模式,三种模式虽然各不相同,但是有些东西却是相互借鉴的。例如,简单工厂模式是最简单的,它就只有一个被称为工厂的类,在这个类里面,可以实例化所有的对象;工厂模式也有工厂类,不过是有多个,具体地说就是一个对象对应一个工厂类,并且这些工厂类都继承了一个共同的接口,下面先介绍工厂模式:
假设保险公司有五种保险,分别是:人身伤亡险、碰撞险、司机受伤险、综合险和财产损失险,要求是使用工厂模式设计并实现一个可以创建不同保险理赔对象的应用。
具体的思路就是:1、分别创建这几种保险的类,并且都要继承一个接口(方便调用)
2、新建一个接口,这个接口有一个方法,这个方法可以返回上述对象的方法;然后就是为每种保险新建一个工厂类,并且都要继承前面的接口。
保险的接口:
public interface AutoInsurance1 {
abstract String getInsurInfo();
}
人身伤亡险类:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package factory;
/**
*
* @author Administrator
*/
public class BodyInjur1 implements AutoInsurance1{
private String description;
public String getInsurInfo()
{
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;
}
}
其他保险类省略。
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package factory;
/**
*
* @author Administrator
*/
public interface PolicyProducer_f {
public AutoInsurance1 getPolicyObj();
}
其中一个工厂类:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package factory;
/**
*
* @author Administrator
*/
public class BodyInjurPolicyProducer implements PolicyProducer_f{
public AutoInsurance1 getPolicyObj() //Fruit factory()
{
return new BodyInjur1();
}
}
其他工厂类省略。
主方法中选择工厂类的部分代码:
PolicyProducer_f pp = null;
if (str.equalsIgnoreCase("人身伤亡")) {
pp = new BodyInjurPolicyProducer();
} else if (str.equalsIgnoreCase("碰撞")) {
pp = new CollisionPolicyProducer();
} else if (str.equalsIgnoreCase("司机受伤")) {
pp = new PersonInjuryPolicyProducer();
} else if (str.equalsIgnoreCase("综合险")) {
pp = new ComprehensivePolicyProducer();
} else if (str.equalsIgnoreCase("财产损失")) {
pp = new PropertyDamagePolicyProducer();
}
AutoInsurance1 ai = pp.getPolicyObj();
String desc = ai.getInsurInfo();