Java design mode GOF23 02 Factory mode

Source: Internet
Author: User

Package com.lz.factory.simpleFactory;/** * Supplement: Object-oriented Principles * OCP: (open and closed principle) adding new features should not modify the original code, but instead add a new class * DIP: (Dependency Reversal Principle) dependency programming * LOD: (Dimitri Law) reduces coupling, communicates only with necessary objects * Static Factory class {* Creator and Separation of callers * Simple factory problem: Adding a new feature requires a code change *} * Factory method class {* Code too Much *} * Comparison of the two * simple factory structure Code simpler * Factory method is more difficult to maintain * Summary: The factory method model conforms to the theoretical requirements but the actual use of more simple Factory mode selection *  */ Public classSimplefactory { Public StaticCar Createcar (String msg) {if(Msg.equals ("Jeep")) {            return NewJeep (); } Else if(Msg.equals ("BMW")) {            return NewBMW (); } Else {            return NULL; }    }}

Package com.lz.factory.simpleFactory; /* * Automotive Interface   */  Public Interface Car {    publicvoid  run ();}
 package com.lz.factory.simpleFactory;  public  class   BMW implements car{@Override  public  
   
    void  
     run () {System.  
    out . println (
     " 
    i am BWM  
     "    
    ); }}
   
Package com.lz.factory.simpleFactory;  Public class Jeep implements car{    @Override    publicvoid  run () {        System. out. println ("I am Jeep");}    }
Package com.lz.factory.simpleFactory; Public classTest01 { Public Static voidMain (string[] args) {Car BMW=NewBMW (); Car Jeep=NewJeep ();        Bmw.run ();        Jeep.run (); Car BMW1= Simplefactory.createcar ("BMW"); Car Jeep1= Simplefactory.createcar ("Jeep");        Bmw1.run ();    Jeep1.run (); }}

Factory Method Class:

Add a factory method to each of the classes

Package Com.lz.factory.factoryMethod; /*  */Publicinterface  carfactory {    Car createcar ();}

Java design mode GOF23 02 Factory mode

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.