• Category: Structural
  • Type: object
  • Motivation: prefer composition over inheritance, implementation detail are pushed from a hierarchy to another object with a separate hierarchy.

diagram

do {
  let about = AboutPage(Light())
  about.render()

  let project = ProjectPage(Dark())
  project.render()
}
protocol Page
{
	init(_ theme: Theme)
	func render()
}

protocol Theme
{
	func colored(_ html: String)
}
class Dark: Theme
{
	func colored(_ html: String)
	{
		print("dark \(html)")
	}
}

class Light: Theme
{
	func colored(_ html: String)
	{
		print("light \(html)")
	}
}
class AboutPage: Page
{
	var theme: Theme

	required init(_ theme: Theme)
	{
		self.theme = theme
	}

	func render()
	{
		theme.colored("about")
	}
}

class ProjectPage: Page
{
	var theme: Theme

	required init(_ theme: Theme)
	{
		self.theme = theme
	}

	func render()
	{
		theme.colored("about")
	}
}