Start learning free

LESSON 315 OF 343 · DESIGN PATTERNS

Factory Method Pattern in Python

Practice Creational

Sometimes shared code must create an object, but which kind depends on the case. The Factory Method pattern leaves that choice to one method that each subclass overrides. The shared code then works with whatever object it gets, with no if on the kind.

Here you build a delivery company that ships by road or by sea.

The base class Transport has one method, cost(km). It returns the price of one delivery of km kilometres. Each class built on it overrides cost. That means it writes its own cost, and that one runs.

Write two classes built on it:

  • Truck() costs 50 + 3 * km.
  • Ship() costs 500 + km.

Then write the base class Logistics, with two methods:

  • create_transport() is the factory method. It has no real body here, and each subclass overrides it to return a new transport.
  • deliver(km) is written once, in Logistics. It calls create_transport() and returns that transport's cost(km).

Two classes are built on Logistics. Each overrides create_transport() and nothing else:

  • RoadLogistics() returns a new Truck.
  • SeaLogistics() returns a new Ship.

The tests make the two logistics once, as in road = RoadLogistics(). Then they only call road.deliver(km) and sea.deliver(km). They never make a Truck or a Ship themselves. So each price comes from the factory method of road or sea.

Each call of deliver writes one line: the price.

 

Example 1:

Input:
1. road.deliver(1)
2. sea.deliver(1)
3. road.deliver(100)
4. sea.deliver(100)
Output:
53
501
350
600
Explanation:
Call 1: road makes a new Truck. It costs 50 + 3 * 1 = 53.
Call 2: sea makes a new Ship. It costs 500 + 1 = 501.
Call 3: a truck for 100 km costs 50 + 300 = 350.
Call 4: a ship for 100 km costs 500 + 100 = 600.
On short trips the truck is cheaper.

Example 2:

Input:
1. road.deliver(225)
2. sea.deliver(225)
3. road.deliver(1000)
4. sea.deliver(1000)
Output:
725
725
3050
1500
Explanation:
Calls 1 and 2: at 225 km, both cost 725.
Call 3: a truck for 1000 km costs 50 + 3000 = 3050.
Call 4: a ship for 1000 km costs 500 + 1000 = 1500.
On long trips the ship is cheaper.

 

Constraints:

  • km is a whole number from 1 to 100,000.
  • A price is at most 300,050.
  • At most 100,000 calls of deliver.

Note:

Each call should run in O(1) time. It makes one new transport and asks it for one price.

STEP 1 OF 15
    Ctrl + Enter to check

    Factory Method Pattern in Python

    Keep going with Python1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free