Factory Method

interface IFactory {
	public IProduct produce();
}
interface IProduct {
	public void drive();
}

public class FactoryMethod {

	public static void main(String[] args) {
		
		IFactory carFac = new CarFactory();
		IProduct car = carFac.produce();
		car.drive();
		
		IFactory busFac = new BusFactory();
		IProduct bus = busFac.produce();
		bus.drive();
	}
}
class CarFactory implements IFactory {
	@Override public IProduct produce() {
		return new Car();
	}
}
class BusFactory implements IFactory {
	@Override public IProduct produce() {
		return new Bus();
	}
}

class Car implements IProduct {
	@Override public void drive() {
		System.out.println("Car is driving......");
	}
}
class Bus implements IProduct {
	@Override public void drive() {
		System.out.println("Bus is driving......");
	}
}

 

 * The advantage of the factory pattern is that the coupling between the factory and the product is reduced, and the construction process of the specific product is placed in the specific factory class.
   It is much more convenient to expand products in the future. You only need to add a factory class and a product class, and you can easily add products without the need for

   Modify the original code.

 * Intent: Define an interface for creating objects and let subclasses decide which class to instantiate. Factory Method instantiates a class

    Delay to its subclasses.


 * Applicability:
    When a class does not know the class of the object it must create.
    When a class wants its subclasses to specify the objects it creates. 
    When a class delegates object creation to one of several helper subclasses, and you want which helper subclass to be the proxy

    When information is localized.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=327037859&siteId=291194637