Design patterns

Factory Method Pattern

Factory Method Pattern defines an interface for creating an object, but lets subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.

Factory Method Pattern:

defines an interface for creating an object, but lets subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.

Design principles:

  • Designs should be open for extension but closed for modification
  • Depend upon abstractions, do not depend upon concrete classes
  • Dependency inversion principle – high-level components should not depend on low-level components, but both types should depend on abstractions
  • Variables should not hold references to concrete classes
  • Classes should not derive from concrete classes
  • Methods should not override implemented methods in base classes

Factory Method Pattern encapsulates object creation. Abstract Creator class gives an interface with a “factory method” for creating objects. Methods implemented in the abstract Creator operate on products produced by the “factory method”. Subclasses implement the factory method and create products.

How it works (code example):

public abstract class Bakery {
	public Bun orderBun (String sort) {
		Bun bun;
		bun = bakeBun(sort);
		bun.packageUp();
		return bun;
	}
	abstract Bun bakeBun(String sort);
}
public class SweetsBakery extends Bakery {
	Bun bakeBun(String sort) {
		if (item.equals("curd")) {
			return new CurdBun;
		} else if (item.equals("cream")) {
			return CreamBun;
		}
	}
}
public abstract class Bun {
	String name;
	String filling;
	void packageUp() {
		System.out.println ("Put bun in to the box");
	}
	public String getName() {
		return name;
	}
}
public class CurdBun extends Bun {
	public CurdBun() {
		name = "Curd Bun";
	}
}

public class CreamBun extends Bun {
	public CreamBun() {
		name = "Cream Bun";
	}
}

Let’s run it:

public class Bake {
	public static void main(String[] args) {
		Bakery sweetsBakery = new SweetsBakery();
		Bun bun = sweetsBakery.bakeBun("curd");
		System.out.println(bun.getName() + " is baked");
	}
}

Leave a Reply

Your email address will not be published. Required fields are marked *