Skip to content

Commit

Permalink
composite pattern
Browse files Browse the repository at this point in the history
  • Loading branch information
pestsov-v committed Apr 28, 2022
1 parent 1cd9804 commit 27ea2ce
Showing 1 changed file with 48 additions and 0 deletions.
48 changes: 48 additions & 0 deletions structure_patterns/Composite.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
abstract class DeliveryItem {
items: DeliveryItem[]

addItem(item: DeliveryItem) {
this.items.push(item)
}

getItemPrices(): number {
return this.items.reduce((acc: number, i: DeliveryItem) => acc += i.getItemPrices(), 0)
}

abstract getPrice(): number
}

class DeliveryShop extends DeliveryItem {
constructor(private delivaryFee: number) {
super()
}

getPrice(): number {
return this.items.reduce((acc: number, i: DeliveryItem) => acc += i.getItemPrices(), 0) + this.delivaryFee
}
}

class Package extends DeliveryItem {s
getPrice(): number {
return this.getItemPrices()
}
}

class Product extends DeliveryItem {
constructor(private price: number) {
super()
}

getPrice(): number {
return this.price
}
}

const shop = new DeliveryShop(100)
shop.addItem(new Product(1000))
const pack1 = new Package()
pack1.addItem(new Product(200))
pack1.addItem(new Product(300))
shop.addItem(pack1)
const pack2 = new Package()
pack2.addItem(new Product(30))

0 comments on commit 27ea2ce

Please sign in to comment.