Java Simple Factory mode

Source: Internet
Author: User

I. Overview

1. Objective: To control the mode of production of any type of vehicle

2. The target has two meanings (1) any type (2) Production mode, so the corresponding, to this two levels of abstraction (movable,vehiclefactory), the use of interfaces, to achieve polymorphic

Second, class structure

1.Interface Movable.java

2.car.java

3.plane.java

4.Interface Vehiclefactory.java

5.carfactory.java

6.planefactory.java

Third, the Code

1.movable.java

public interface Movable {void run ();

  

2.car.java

Public class car implements movable {public Car () {}public void run () {System.out.println ("Car running ...");}}

  

3.plane.java

Public class Plane implements movable {@Overridepublic void run () {SYSTEM.OUT.PRINTLN ("aircraft flying .... ");}}

  

4.vehiclefactory.java

Public interface Vehiclefactory {movable create ();}

  

5.carfactory.java

public class Carfactory implements Vehiclefactory {private static car car = new car (); @Overridepublic movable Create () {RE Turn Car;}}

  

6.planefactory.java

public class Planefactory implements Vehiclefactory {private static Plane Plane = new Plane (); @Overridepublic movable Crea Te () {return plane;}}

  

7.test.java

public class Test {@org. junit.testpublic void Test () {Vehiclefactory factory = new Carfactory (); Movable m1 = Factory.create (); M1.run (); Movable m2 = factory.create (); SYSTEM.OUT.PRINTLN (m1 = = m2); System.out.println (M1.equals (m2)); System.out.println ("******************************"); factory = new Planefactory (); m1 = Factory.create (); M1.run (); m2 = Factory.create (); SYSTEM.OUT.PRINTLN (m1 = = m2); System.out.println (M1.equals (m2));}}

  

8. Test results

Java Simple 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.