设计模式——工厂模式

参考博客:https://www.cnblogs.com/malihe/p/6891920.html

 

一、静态工厂模式:

实现了统一接口的不同类,通过一个工厂类实现的不同静态方法获取实例

常用的工厂模式是静态工厂,利用static方法,作为一种类似于常见的工具类Utils等辅助效果,一般情况下工厂类不需要实例化。

//学生静态工厂

//统一接口 interface student{ String study();}
//不同类实现统一接口
class BeijingStudent implements student{ @Override public String study() { return "well"; } } class TianjingStudent implements student{ @Override public String study() { return "great"; } } class NanjingStudent implements student{ @Override public String study() { return "good"; } }
//工厂类
public class StudentFactory { private StudentFactory(){}
//静态工厂方法产生实例
public static student getBStuendt(){ return new BeijingStudent(); } public static student getTStudent(){ return new TianjingStudent(); } public static student getNStudent(){ return new NanjingStudent(); } } class StudentClient{ public student get(String name){ if(name.equals("B")) return StudentFactory.getBStuendt(); else if(name.equals("T")) return StudentFactory.getTStudent(); else return StudentFactory.getNStudent(); } }

 

 

二、抽象工厂模式:

实现了统一接口的不同类,通过实现了统一工厂接口的不同工厂类产生实例

优点是:耦合性低,静态工厂在不修改工厂代码的情况下,无法实现新的实例

               而抽象工厂则可以灵活地添加新的工厂类来实现新的实例

interface Person{}

class PersonA implements Person{}
class PersonB implements Person{}

//抽象工厂接口
interface PersonFactory{ Person get();} class FactoryForPersonA implements PersonFactory{ @Override public Person get() { return new PersonA(); } } class FactoryForPersonB implements PersonFactory{ @Override public Person get() { return new PersonB(); } } public class PFactory { Person A = new FactoryForPersonA().get(); Person B = new FactoryForPersonB().get(); }

 

posted @ 2019-03-22 20:15  胡叁安  阅读(138)  评论(0编辑  收藏  举报