Start learning free

LESSON 315 OF 343 · DESIGN PATTERNS

Factory Method Pattern

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 kind writes in its own way. 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 interface Transport has one method, cost(km). It returns the price of one delivery of km kilometres. An interface lists the methods a type must have.

Write two structs that have it:

  • Truck{} costs 50 + 3 * km.
  • Ship{} costs 500 + km.

Then write the interface Logistics, with one method, createTransport(). It is the factory method: each kind of logistics returns its own new transport.

Write the function deliver(logistics, km) once. It calls logistics.createTransport() and returns that transport's cost(km).

Two structs are a Logistics. Each writes its own createTransport() and nothing else:

  • RoadLogistics{} returns a new Truck.
  • SeaLogistics{} returns a new Ship.

Go has no classes and no subclasses. Each transport and each logistics is a struct with no fields, like Truck{}. Any struct with the method createTransport() is a Logistics. So deliver is a plain function, written once for all of them.

The tests make the two logistics once, as in var road Logistics = RoadLogistics{}. Then they only call deliver(road, km) and deliver(sea, 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. deliver(road, 1)
2. deliver(sea, 1)
3. deliver(road, 100)
4. deliver(sea, 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. deliver(road, 225)
2. deliver(sea, 225)
3. deliver(road, 1000)
4. deliver(sea, 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 13
    Ctrl + Enter to check