java常用设计模式二:工厂模式
1、简单工厂模式(静态工厂方法模式)
抽象实例:
public interface People {void talk();
}
具体实例:
public class Doctor implements People {public void talk() {
System.out.println("我是医生");
}
}
public class Teacher implements People {public void talk() {
System.out.println("我是教师");
}
}
具体工厂
public class Factory {public static People createInstance(String flag){
if("doctor".equals(flag)){
return new Doctor();
}
if("teacher".equals(flag)){
return new Teacher();
}
return null;
}
}
测试类:
public class Test {public static void main(String[] args){
People people = Factory.createInstance("doctor");
people.talk();
people = Factory.createInstance("teacher");
people.talk();
}
}
我是医生我是教师
该模式的缺点:增加 具体实例 需要修改工厂类
2、工厂方法模式
抽象实例:
public interface People {void talk();
}
具体实例:
public class Doctor implements People {public void talk() {
System.out.println("我是医生");
}
}
public class Teacher implements People {public void talk() {
System.out.println("我是教师");
}
}
抽象工厂
public abstract class AbstractFactory {abstract People createInstance();
}
具体工厂
public class DoctorFactory extends AbstractFactory {People createInstance() {
return new Doctor();
}
}
public class TeacherFactory extends AbstractFactory {People createInstance() {
return new Teacher();
}
}
测试类:
public class Test {public static void main(String[] args){
AbstractFactory doctorFactory = new DoctorFactory();
AbstractFactory teacherFactory = new TeacherFactory();
doctorFactory.createInstance().talk();
teacherFactory.createInstance().talk();
}
}
我是医生我是教师
该模式的相对于 简单工厂模式 来说,如果要增加新的 具体实例 不需要修改原来的工厂方法,只需要新增一个 具体工厂。缺点就是当 具体实例 很多的时候,会增加很多与之对应的 具体工厂
3、抽象工厂模式
抽象实例和具体实例和前面的一样,此处省略不写
抽象工厂
public interface AbstractFactory {People createDoctorInstance();
People createTeacherInstance();
}
具体工厂
public class ConcreteFactory implements AbstractFactory {public People createDoctorInstance() {
return new Doctor();
}
public People createTeacherInstance() {
return new Teacher();
}
}
测试类:
public class Test {public static void main(String[] args){
AbstractFactory doctorFactory = new ConcreteFactory();
doctorFactory.createDoctorInstance().talk();
doctorFactory.createTeacherInstance().talk();
}
}
我是医生我是教师
该模式缺点和简单工厂模式一样:增加 具体实例 需要修改 工厂类。
4、工厂模式与反射结合,实现新增 具体实例 不需要修改和新增 工厂类
抽象实例和具体实例和前面的一样,此处省略不写
具体工厂
public class ReflectFactory {public People createInstance(String className) throws Exception {
Class<?> cls = Class.forName(className);
People people = (People) cls.newInstance();
return people;
}
}
测试类:
public class Test {public static void main(String[] args) throws Exception {
ReflectFactory reflectFactory = new ReflectFactory();
reflectFactory.createInstance("factory.demo.Doctor").talk();
reflectFactory.createInstance("factory.demo.Teacher").talk();
}
}
我是医生我是教师
以上是 java常用设计模式二:工厂模式 的全部内容, 来源链接: utcz.com/z/389747.html