简单工厂:
为实现同一个接口的类创建对象,工厂类是核心类,由工厂类决定创建那个类的对象
缺点:
当需要扩展的时候,就需要创建实体类,改动工厂类,增加分支,不利于程序的扩展和维护,也违反了开放闭包的原则
public class Operation {
public double getReslt(double a,double b);
}
public class OperationAdd {
public double getReslt(double a,double b) {
return a + b;
}
}
public class OperationDelete {
public double getReslt() {
return a - b;
}
public class OperationFactory {
private Operation operation = null;
public Operation CreateOperation(String str) {
switch(str) {
case '+':
operation = new OperationAdd();
break;
case '-':
operation = new OperationDelete();
break;
}
return operation;
}
}
工厂方法模式:
定义一个用于创建对象的接口,不再由一个工厂类去决定那个产品类被实例化,而是由抽象工厂的子类去决定
优点:
克服了简单工厂违反开放闭包的原则,降低了程序间的耦合
缺点:
每当增加一个类就需要增加一个对应的工厂类,增加额外的开发量
public class LeiFeng{}
public class Student extends LeiFeng{}
public class Volunteer extends LeiFeng{}
Interface IFactory {
Leifeng createOperation();
}
public class StudentFactory implements IFactory {
Leifeng createOperation() {
return Student();
}
}
public class VolunteerFactory implements IFactory {
Leifeng createOperation() {
return Volunteer();
}
}
抽象工厂模式
提供一个创建一系列相关或者相互依赖的对象的接口,而无需指定它们的具体的类(针对的抽象的产品有多个,是一些列产品,当只有一个产品时,就退化到了工厂模式)
优点:在于方便的交换系列产品,比如:数据库的使用(Sql Server,Access),网络请求框架的使用
缺点:当需要增加功能时,改动比较大
public Inteface IDepartment {
void insert(Department department);
Department getDepartment(int userId);
}
public class SqlServerDepartment implements IDepartment {
void insert(Department department) {}
Department getDepartment(int userId) {}
}
public class AccessDepartment implements IDepartment {
void insert(Department department) {}
Department getDepartment(int userId) {}
}
public Inteface IUser {
void insert(Department department);
User getUser(int userId);
}
public class SqlServerUser implements IUser {
void insert(User user) {}
User getUser(int userId) {}
}
public class AccessUser implements IUser {
void insert(User user) {}
User getUser(int userId) {}
}
public Inteface IFactory {
IUser createUser();
IDepartment createDepartment();
}
public class SqlServerFactory implements IFactory {
public IUser createUser() {
return new SqlServerUser();
}
IDepartment createDepartment() {
return new SqlServerUser();
}
}
public class AccessFactory implements IFactory {
public IUser createUser() {
return new AccessUser();
}
IDepartment createDepartment() {
return new AccessDepartment();
}
}