工厂模式(factory pattern)

工厂模式(factory pattern)

有时候我们在创建一个类的时候可能需要大量代码,如果把这个创建逻辑都放在一个类中完成,那无疑是非常冗余的,而且如果代码作为一个底层支持,我们需要对调用方提供干净的支持,他们无需了解如何创建对象的细节,只需要使用即可。所以我们使用工厂模式,把我们的工具或类者业务类组合起来成一个个产品,而创建产品的类就是工厂类,这个模式称为工厂模式, 通常有

  • 简单工厂(工厂方法(F抽象工厂(Abstract Factory Pattern)我们需要针对不同的业务场景,使用不同的模式,下面进行逐一阐述。

 Simple Factory Pattern

It is up to a factory object to decide which instance of a product class to create

 first: To create a interface that othere implementation class will implement, the key point is other  implementation class  must be a same series,as you can see from code below,ArithmeticCourse and JavaCourse are same series -> Course

public interface ICourse {
    void study();
}
public class ArithmeticCourse implements ICourse {
    public void study() {
        System.out.println("study Arithmetic");
    }
}
public class JavaCourse implements ICourse {
    public  void  study(){
        System.out.println("study Java");
    }
}

second: 

To create a factory that all same series implementions class are created by

public class CourseFactorty {

    public ICourse create(Class<? extends ICourse> clazz) {
        try {
            return clazz.newInstance();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}

Using in 

Calendar->getInstance->createCalendar,as you see that case in switch are chosen to create factory by key-character

 LoggerFactory->getLogger,the factory are created by key-character as well

 

 sum up:

advantage:

  • simple(use): you just need transfer  parameters that you want to create factory

disadvantage:

  • complex(class of creating factory):As demand increases, the classes that create factories are certainly hard to maintain

Factory Method  Pattern

Define an interface for creating an object,but let subclassess decide which class to instantiate. The Factory method lets a class defer instantiation it uses to sublasses

 

 1. to create a interface that all factories will be created by

public interface ICourseFactory {
    ICourse creat();
}

2.to create classes of factories implementing IcourseFactory,all relevant class will be created from them

public class JavaCourseFactory implements ICourseFactory {
    public ICourse creat() {
        return new JavaCourse();
    }
}
public class ArithmeticFactory implements ICourseFactory {
    public ICourse creat() {
        return new ArithmeticCourse();
    }
}

3.Test,client have to know that name of factory then use class of factory to create

    public static void main(String[] args) {
        ICourseFactory iCourseFactory=new JavaCourseFactory();
        ICourse creat = iCourseFactory.creat();
        creat.study();
    }

Using in 

org.slf4j.ILoggerFactory is a good example for factory method pattern,we can see it from class diagram,all classes of factory implement the top of interfance of ILoggerFactory.

 sum up:

advantage:

  • follow Open/Closed Principle: we just need  add a new factory, if we want to add a new product 

disadvantage:

  • complexity of system and classess: there are lot of classess in the system, which is bound to spend much time  for a new person to recognizing the system

Factory Method  Pattern

 Provide an interface for creating families of related  or dependent objects without specifying their concrete classess

 this is a picture that i got from Internet descripting the abstruct factory pattern.visibly,product families (产品族) consist of Products class structure(产品等级结构).So,first We should structure Products class structure.To illustrate,for example , now days ,There are many school online and They have things in common,which is to make course like course of java、arithmetic and each course should be have note and record. so , products familiy consist of  courses ( java、arithmetic) and    Products class structure consist of restrict conditions(note、video) . let us start with Products class structure(产品等级结构).

create interface to set regulation

public interface IVideo {
    void  record();

}
public interface INote {
    void  edit();
}

then each products to  implement regulation

public class ArithmeticNote implements INote {
    public void edit() {
        System.out.println("Arithmetic edit");
    }
}
public class ArithmeticVideo implements IVideo{
    public void record() {
        System.out.println("Arithmetic record ");
    }
}
public class JavaNote implements INote {
    public void edit() {
        System.out.println("java edit");
    }
}
public class JavaVideo implements IVideo {
    public void record() {
        System.out.println("java record ");
    }
}

To set regulation that each product(Java、arithmetic) have to obey,which can be a abstract class or interface,as you see if you want have some public function to run before or after these implementation class run. you must to create an abstract class.

public abstract  class CourseFactory {
    public void init(){
        System.out.println("init..");
    }
    protected abstract INote createNote();
    protected abstract IVideo createVideo();
}

To create  subclasses and each  subclasses  to create themself product

public class JavaCourseFactory extends CourseFactory {
    protected INote createNote() {
        super.init();
        return new JavaNote();
    }

    protected IVideo createVideo() {
        super.init();
        return new JavaVideo();
    }
}
public class ArithmeticCourseFactory extends  CourseFactory {
    protected INote createNote() {
        super.init();
        return new ArithmeticNote();
    }

    protected IVideo createVideo() {
        super.init();
        return new ArithmeticVideo() ;
    }
}

To test

public class Test {
    public static void main(String[] args) {
        CourseFactory javaCourseProduct=new JavaCourseFactory();
        javaCourseProduct.createNote().edit();
        javaCourseProduct.createVideo().record();

        CourseFactory arithmeticCourseProduct=new ArithmeticCourseFactory();
        arithmeticCourseProduct.createVideo().record();
        arithmeticCourseProduct.createNote().edit();
    }
}

conclusion

Factory Method Pattern is more popular than other factory pattern, abstract factory is pretty complex(there are many classes in a  project,it seem to be prefect in design,but should spend much time for a new person to recognizeing system ),and simple factory is kind of simple(if we should add a new product means we should edit class of factory).

原文地址:https://www.cnblogs.com/UpGx/p/14623101.html