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 interface ITransport has one method, Cost(km). It returns the price of one delivery of km kilometres. An interface lists the methods a class promises to have.
Write two classes that implement it:
new Truck()costs50 + 3 * km.new Ship()costs500 + km.
Then write the abstract class Logistics, with two methods:
CreateTransport()is the factory method. It is abstract: it has no body, and each subclass overrides it to return a new transport.Deliver(km)is written once, inLogistics. It callsCreateTransport()and returns that transport'sCost(km).
Two classes are built on Logistics. Each overrides CreateTransport() and nothing else:
new RoadLogistics()returns a newTruck.new SeaLogistics()returns a newShip.
The tests make the two logistics once, as in Logistics road = new 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:
kmis 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.
Free plan: 30 tutor messages. PRO is unlimited.
