Myšlenkou tohoto principu je, že existující třídy by měly být rozšířeny, ale ne modifikovány. Úpravou existujících tříd riskujete porušení kódu, který již byl testován a zkontrolován.
Hlavní výhodou tohoto principu je, že můžete přidávat nové funkce, aniž byste se dotkli starého kódu. Tímto způsobem nenarušíte současné používání těchto původních tříd.
V následujícím špatném příkladu můžeme vidět, jak Order
třída počítá náklady na dopravu pro každý ze stávajících způsobů dopravy.
class Order {
id: number;
items: string[];
shipping: string;
// constructor
getTotalCost(): number {
// calculates total cost
}
getShippingCosts(): number {
const totalCost = this.getTotalCost();
if (this.shipping === "ground") {
return totalCost > 50 ? 0 : 5.95;
}
if (this.shipping === "air") {
return 10.95;
}
return 0;
}
}
Pokud bychom chtěli přidat nový způsob dopravy, museli bychom upravit Order
třída. Podle principu Open/Closed to můžeme vyřešit vytvořením rozhraní a třídy, která jej implementuje pro každý způsob dopravy.
class Order {
id: number;
items: string[];
shipping: Shipping;
// constructor
getTotalCost(): number {
// calculates total cost
}
}
interface Shipping {
getShippingCosts(totalCost: number): number;
}
class Ground implements Shipping {
getShippingCosts(totalCost: number): number {
return totalCost > 50 ? 0 : 5.95;
}
}
class Air implements Shipping {
getShippingCosts(): number {
return 10.95;
}
}
class PickUpInStore implements Shipping {
getShippingCosts(): number {
return 0;
}
}