The Kungfu in scala programming
Definition in GOF (the Gang of Four)
Descriptions of communicating objects and classes that are customized to
solve a general design problem in a particular context.
Design pattern space
Creational Purpose
Class Scope
- Factory Method Wiki Cubean Blog
Object Scope
- Abstract Factory Wiki Cubean Blog
- Builder Cubean Blog
- Prototype Cubean Blog
- Singleton Wiki Cubean Blog
Structural Purpose
Class Scope
- Adapter(class)
Object Scope
- Adapter(object)
- Bridge
- Composite
- Decorator
- Facade
- Flyweight
- Proxy
Behavioral Purpose
Class Scope
- Interpreter
- Template Method
Object Scope
- Chain of Responsibility
- Command
- Iterator
- Mediator
- Memento
- Observer
- State
- Strategy
- Visitor
Language Features and Patterns
A typical singleton implementation in Java language:
1 |
public class { |
A typical singleton implementation in Scala language:
1 |
object { |
Factory Method
Description
Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to sub- classes.
1 |
trait Product { |
Output:
1 |
Set(Milk(0.99), Sugar(1.49), Milk(0.79)) |
Abstract Factory
Description
Provide an interface for creating families of related or dependent objects without specifying the concrete classes.
Focus on Encapsulation
Sometimes, A factory defined both products and process and hide all details but just output object with general format.
1 |
object AnimalFactory { private trait Animal private case class Dog(name : String = "doggy") extends Animal private case class Cat(name : String = "cat") extends Animal |
Client
1 |
MyAnimalFactory.createAnimal("dog") |
Sometimes, a factory just defined and hide process then output object defined in outside.
1 |
trait Animal case class Dog(name : String) extends Animal case class Cat(name : String) extends Animal |
Client
MyAnimalFactory.createAnimal("dog")
res14: Animal = Dog(doggy)
近期评论