Creational Design Patterns in C#: Building Flexible and Scalable Software by Vaskaran Sarcar

Creational Design Patterns in C#: Building Flexible and Scalable Software by Vaskaran Sarcar

Author:Vaskaran Sarcar
Language: eng
Format: mobi
ISBN: 9798868815676
Publisher: Apress
Published: 2025-07-15T00:00:00+00:00


PRIMARY CONSTRUCTOR MAKES THE CODE CONCISE

Using the Primary constructor (introduced in C#12) and removing the _type field, you can make the Car class concise as follows:

#region The code segment that uses a primary constructor

class Car(string type)

{

/*

* You can use any data structure that you prefer.

* I have used LinkedList<String> in this case.

*/

private LinkedList<string> _parts = new();

// There are no other changes in the remaining code

#endregion

You can make similar changes in equivalent code as well. I showed you the code with and without primary constructors to make you familiar with both approaches. Sometimes I avoid writing code that is very specific to the C# programming language because many C# developers are Java developers as well. In fact, the preface of the classical GoF book says that the design patterns require neither unusual language features nor amazing programming tricks with which to astound your friends and managers. However, you can have a different thought. So, you can choose the approach that serves you best.

Typically, a builder interface is needed for creating parts of a Product object. In our example, Builder is an abstract class that plays this role. It contains the methods to build different parts of a product.

In this example, you see an empty method, called AddExhaustSystem, in the Builder class. Why? Ideally, this class should define all possible methods to build various parts of a product (in our example, a car). We can assume that an electric car does not need an exhaust emission system, whereas a traditional car must have such a component. I could make other methods in the Builder class empty as well; however, I forced the concrete builders to implement those methods.

There is another method, called GetCar, in this class. This method retrieves the product once the parts are assembled. Let’s have a look at this class now:

abstract class Builder

{

public abstract void SetMotor();

public abstract void InsertWheels();

public abstract void SetHeadlights();

// The exhaust emissions system is needed for regular cars

public virtual void AddExhaustSystem() { }

// To retrieve the constructed product.

public abstract Car GetCar();

}

In the upcoming examples, the TraditionalCarBuilder and ElectricCarBuilder classes make the traditional cars and electric cars, respectively. In other words, these are the concrete builders that build the internal representations of a Car instance. First, see the ElectricCarBuilder class:

// The ElectricCarBuilder builds electric cars.

class ElectricCarBuilder : Builder

{

private readonly Car _car;

public ElectricCarBuilder()

{

_car = new("electric");

}

public override void SetMotor()

{

_car.Motor = "electric motors and batteries";

_car.Add($"The {_car.Motor} are added.");

}

public override void InsertWheels()

{

_car.Wheels = 4;

_car.Add($"{_car.Wheels} wheels are added to the car.");

}

public override void SetHeadlights()

{

_car.HeadLights = 2;

_car.Add($"{_car.HeadLights} headlights are set.");

}

// NOTE: The electric car does not need the exhaust

// emission system. So, we do not need to override the base

// class method.

// Retrieve the constructed car

public override Car GetCar()

{

return _car;

}

}

Now see the TraditionalCarBuilder class (notice that it overrides the AddExhaustSystem method as well):

// The TraditionalCarBuilder builds traditional cars.

class TraditionalCarBuilder : Builder

{

private readonly Car _car;

public TraditionalCarBuilder()

{

_car = new("traditional");

}

public override void SetMotor()

{

_car.Motor = "internal combustion engine (fueled by diesel)";

_car.Add($"The {_car.Motor} is added.");

}

public override void InsertWheels()

{

_car.Wheels = 6;

_car.Add($"{_car.Wheels} wheels are added to the car.");

}

public override void SetHeadlights()

{

_car.



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.
Popular ebooks
Eco-friendly approach of bio-indigo synthesis and developing purification methods towards isolation of indigo from indirubin and bacterial fragments by Ramalingam Manivannan & Kaliyan Prabakaran & Young-A Son(206129)
Personalized inhaled bacteriophage therapy for treatment of multidrug-resistant Pseudomonas aeruginosa in cystic fibrosis by unknow(174573)
CONSORT 2025 statement: updated guideline for reporting randomized trials by unknow(83007)
Critical evaluation of the ProfiLER-02 study design and outcomes by Vivek Subbiah & Razelle Kurzrock(82676)
Cardiac gene therapy makes a comeback by Oliver J. Müller & Susanne Hille & Anca Kliesow Remes(82486)
Whisky: Malt Whiskies of Scotland (Collins Little Books) by dominic roskrow(74436)
Unveiling the design rules for tunable emission in graphene quantum dots: A high-throughput TDDFT and machine learning perspective by Şener Özönder & Mustafa Coşkun Özdemir & Caner Ünlü(50890)
A yeast-based oral therapeutic delivers immune checkpoint inhibitors to reduce intestinal tumor burden by unknow(40259)
Covalent hitchhikers guide proteins to the nucleus by Alexander F. Russell & Madeline F. Currie & Champak Chatterjee(40215)
Meet the Authors: Christopher R. Mansfield and Emily R. Derbyshire by Christopher R. Mansfield & Emily R. Derbyshire(40092)
Alkaline-earth metals promote propane dehydrogenation with carbon dioxide through geometric effects: Altering the reaction pathway by unknow(32729)
Induced iron vacancies boosting FeOOH loaded on sustainable Fenton-like collagen fiber membrane for efficient removal of emerging contaminants by unknow(32504)
Efficient electric-field-assisted photochemical conversion of methane to n-propanol exclusively over penetrated TiO2Ti hollow fibers by Guanghui Feng(32452)
Bi2SiO5 nanosheets as piezo-photocatalyst for efficient degradation of 2,4-Dichlorophenol by Hangyu Shi & Yifu Li & Lishan Zhang & Guoguan Liu & Qian Zhang & Xuan Ru & Shan Zhong(32383)
A novel NDIPTA organic heterojunction photocatalyst with built-in electric field for efficient hydrogen production by Jiahui Yang & Baojun Ma & Yongfa Zhu(32360)
Enhanced conversion of methane to liquid-phase oxygenates via hollow ferrite nanotube@horseradish peroxidase based photoenzymatic catalysis by Jun Duan & Shiying Fan & Xinyong Li & Shaomin Liu(32330)
Ordered macroporous superstructure of defective carbon adorned with tiny cobalt sulfide for selective electrocatalytic hydrogenation of cinnamaldehyde by Xiao-Shi Yuan & Sheng-Hua Zhou & San-Mei Wang & Wenbo Wei & Xiaofang Li & Xin-Tao Wu & Qi-Long Zhu(32256)
What's Done in Darkness by Kayla Perrin(27144)
Topological analysis of non-conjugated ethylene oxide cored dendrimers decorated with tetraphenylethylene: Insights from degree-based descriptors using the polynomial approach by A Theertha Nair & D Antony Xavier & Annmaria Baby & S Akhila(26522)
Investigation of mechanical and self-healing properties of hydroxyl-terminated polybutadiene functionalized with 2-ureido-4-pyrimidinone by Mohsen Kazazi & Mehran Hayaty & Ali Mousaviazar(26457)