简单工厂模式(案例):
1.公用接口Salary
package com.design.simplefactory;
public interface Salary {
void computerSalery();
}
2.实现接口的类:BeiJingSalary
package com.design.simplefactory;
public class BeiJingSalary implements Salary {
@Override
public void computerSalery() {
System.out.println("computer BeiJing Salary");
}
}
3.实现接口的类:HeiBeiSalary
package com.design.simplefactory;
public class HeiBeiSalary implements Salary {
@Override
public void computerSalery() {
System.out.println("computer HeiBei salary");
}
}
4.负责对象的创建(简单工厂也叫静态工厂):SimpleFactory
package com.design.simplefactory;
public class SimpleFactory {
public static Salary createSalary(String className){
try {
Class cls = Class.forName(className);
Salary salary = (Salary) cls.newInstance();
return salary;
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return null;
}
}
5.客户端调用:Client
package com.design.simplefactory;
public class Client {
public static void main(String[] args){
Salary salary = SimpleFactory.createSalary("com.design.simplefactory.HeiBeiSalary");
salary.computerSalery();
salary = SimpleFactory.createSalary("com.design.simplefactory.BeiJingSalary");
salary.computerSalery();
}
}
优点:客户端不再负责对象的创建,而把这个责任丢给了具体的工厂类SimpleFactory,客户端只负责对对象的调用,从而明白了各个类的职责。
缺点:后期不容易维护(考虑到具体产品的不断增多)
适用于:要创建的具体对象比较少或简单的情况下。