Member-only story

Abstract Factory design pattern

In Simple: Factory of Factories

  • EconomicCarFactory: Produces economic car variants.
  • LuxuryCarFactory: Produces luxury car variants.
  • Abstract Factory (e.g., CarProducer) decides which factory to use. shall we use economic car factory or luxury car factory and best on that will car.

Step-by-Step Code

  1. Define the Car Protocol:
    This protocol will represent the properties and methods that each car will implement.
protocol Car {  
var name: String { get }
func drive() -> String
}

2. Implement Concrete Car Classes:
We will create specific implementations for both Economy and Luxury cars.

class EconomyCar1: Car {  
var name: String { return "Economy Car 1" }
func drive() -> String { return "Driving an Economy Car 1" }
}

class EconomyCar2: Car {
var name: String { return "Economy Car 2" }
func drive() -> String { return "Driving an Economy Car 2" }
}

class LuxuryCar1: Car {
var name: String { return "Luxury Car 1" }
func drive() -> String { return "Driving a Luxury Car 1" }
}

class LuxuryCar2: Car {
var name: String { return "Luxury Car 2" }
func drive() -> String { return "Driving a Luxury Car 2" }
}

--

--

No responses yet