Skip to content

Instantly share code, notes, and snippets.

@rommansabbir
Created January 24, 2022 01:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rommansabbir/f4325064a614b4368197ea619b5f4008 to your computer and use it in GitHub Desktop.
Save rommansabbir/f4325064a614b4368197ea619b5f4008 to your computer and use it in GitHub Desktop.
Composite Design Pattern - Kotlin
class CompositeDesignPattern {
companion object {
@JvmStatic
fun main(args: Array<String>) {
/*Create primary products for main catalog*/
val mJeanProduct: CatalogComponent = Product("M: Jeans 32", 65.00)
val mTShirtProduct: CatalogComponent = Product("M: T Shirt 38", 45.00)
/*Create a composite product catalog and add female products to it*/
val newCatalog: CatalogComponent = ProductCatalog("Female Products")
val fJeans: CatalogComponent = Product("F: Jeans 32", 65.00)
val fTShirts: CatalogComponent = Product("F: T Shirt 38", 45.00)
newCatalog.add(fJeans)
newCatalog.add(fTShirts)
/*Create a composite product catalog and add kid products to it*/
val kidCatalog: CatalogComponent = ProductCatalog("Kids Products")
val kidShorts: CatalogComponent = Product("Return Gift", 23.00)
val kidPlayGears: CatalogComponent = Product("Summer Play Gear", 65.00)
kidCatalog.add(kidShorts)
kidCatalog.add(kidPlayGears)
/*Create primary catalog and add primary products and new catalogs to it*/
val mainCatalog: CatalogComponent = ProductCatalog("Primary Catalog")
mainCatalog.add(mJeanProduct)
mainCatalog.add(mTShirtProduct)
mainCatalog.add(newCatalog)
mainCatalog.add(kidCatalog)
/*Print out product/catalog information*/
mainCatalog.print()
}
}
}
abstract class CatalogComponent {
open fun add(catalogComponent: CatalogComponent) {
throw UnsupportedOperationException("Cannot add item to catalog.")
}
open fun remove(catalogComponent: CatalogComponent) {
throw UnsupportedOperationException("Cannot remove item from catalog.")
}
open val name: String
get() {
throw UnsupportedOperationException("Cannot return name.")
}
open val price: Double
get() {
throw UnsupportedOperationException("Cannot return price.")
}
open fun print() {
throw UnsupportedOperationException("Cannot print.")
}
}
class Product(override val name: String, override val price: Double) : CatalogComponent() {
override fun print() {
println("Product name: $name Price: $price")
}
}
class ProductCatalog(override val name: String) : CatalogComponent() {
private val items = ArrayList<CatalogComponent>()
override fun print() {
for (comp in items) {
comp.print()
}
}
override fun add(catalogComponent: CatalogComponent) {
items.add(catalogComponent)
}
override fun remove(catalogComponent: CatalogComponent) {
items.remove(catalogComponent)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment