Realistic use case for static factory method?

前端 未结 6 900
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-02 17:01

I\'m familiar with the idea and benefits of a static factory method, as described in Joshua Bloch\'s Effective Java:

  • Factory methods have names, so you can have mo
6条回答
  •  醉梦人生
    2021-02-02 17:38

    The simple case. Suppose you have a class which operates some sort of printer, but it doesn't care if it is epson, canon or something else. So, you just create an Interface Printer, create some implementations of it and create a class which has only one method: createPrinter.

    So, the code will be simple:

       public interface Printer {
           print();
        }
    
        class CanonPrinter implements Printer {
           print() {
        // ...
           }
        }
    
    
        public PrinterFactory {
    
        Printer createPrinter() {
       if (... ) {
          return new CanonPrinter();
       } else {
          return new EpsonPrinter();
       }
    }
    }
    

    client code:

    Printer printer = PrinterFactory.createPrinter();
    printer.print();
    

    Here you abstract you clinet code from any details of what printers you can operate with or how they manage printing. It's PrinterFactory who cares what printer to choose if one for example malfunctions.

提交回复
热议问题