Design Patterns Flashcards

1
Q

What is Observer pattern?

A

“Define a one-to-many dependency between objects so that when one object changes state, all of its dependents are notified and updated automatically.”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Why do we need Observer pattern?

A

The Observer pattern allows you to notify parts of your program that some other part of your program has changed.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Can you give me an example of Observer pattern?

A

class Chernobyl

attr_reader :observers, :radition_level

def initialize
@observers = []
@radition_level = 0
end

def radition_level_increased
@radition_level += 1
notify_observers
end

def add_observer(observer)
observers &laquo_space;observer
end

  def remove_observer(observer)
    observers.delete(observer)
  end
  def notify_observers
    observers.each do |observer|
      observer.notify(self)
    end
  end

end

class Scientist
  def notify(stantion)
    p stantion.radition_level
  end
end
director = Scientist.new
worker = Scientist.new

chernobyl = Chernobyl.new

chernobyl. add_observer director
chernobyl. add_observer worker

chernobyl. radition_level_increased
chernobyl. radition_level_increased

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What are the key components of Observer pattern?

A
  • field_updated
  • notify_observers
  • add_observer
  • remove_observer
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Can you give example of the simplest observer?

A

$a = 1

def update
  $a = $a + 1
  puts 'Notification was sent'
  # email.to('adaw@gmail.com', 'awdawd@ffea.go')
end

update
update
update

p $a

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What is Decorator pattern?

A

The Decorator pattern allows us to add behavior to a given object without having to add that behavior to the class of the object.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Can you give example of Decorator pattern?

A
class Person
  attr_reader :name, :surname
  def initialize(name, surname)
    @name = name
    @surname = surname
  end

end

class DecoratedPerson
  attr_reader :person
  def initialize(person)
    @person = person
  end

def full_name
“#{person.name} #{person.surname}”
end
end

person = Person.new(‘Leo’, ‘Messi’)
p DecoratedPerson.new(person).full_name

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What are the key component of Decorator?

A

1) Object

2) The method which adds additional behavior/state to this object

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What is Factory method pattern?

A

Factory method is a creational design pattern which solves the problem of creating product objects without specifying their concrete classes.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Can you provide example of Factory Method pattern?

A
class ShapeFactory
  def shape(name)
    case name
    when 'Circle'
      Circle.new
    when 'Square'
      Square.new
    when 'Rectangle'
      Rectangle.new
    end
  end
end
class Circle
  def create
    'Circle was created'
  end
end
class Square
  def create
    'Square was created'
  end
end
class Rectangle
  def create
    'Rectangle was created'
  end
end

p ShapeFactory.new.shape(‘Rectangle’).create

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What are the key components of Factory Method pattern?

A

1) Products classes ( which factory going to return )
2) Method (which every product has)
3) Factory method ( returns one of the Product class )
4) Run method

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What is Abstract Factory Pattern?

A

Abstract Factory is a creational design pattern, which solves the problem of creating entire product families without specifying their concrete classes.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Can you give me an example of abstract factory?

A
class Furniture
  def self.get_furniture(type)
    case type
    when 'English'
      EnglishFurnitureFactory.new
    when 'Europe'
      EuropeFurnitureFactory.new
    end
  end
end
class EnglishFurnitureFactory
  def factory_method(type)
    # chair
    # table
  end
end

class EuropeFurnitureFactory
def factory_method(type)
end
end

p Furniture.get_furniture(‘English’).factory_method(‘Chair’)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What are the key elements of Abstract Fatories?

A

1) Many Product Factories ( with defined factory method)

2) One main factory_method to define which to select

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

What is Singleton pattern?

A

Singleton is a creational design pattern, which ensures that only one object of its kind exists and provides a single point of access to it for any other code

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Can you give me example of Singleton class?

A
class Config
  attr_reader :instance

def self.instance
@instance ||= new
end

private_class_method :new
end

Config.instance

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

What is Command pattern?

A

Command is behavioral design pattern that converts requests or simple operations into objects.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

Can you provide a simple example of Command pattern?

A
class TurnOnLight
  def execute
    'Light was turn on'
  end
end

def run(command)
command.execute
end

p run(TurnOnLight.new)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

What are the key element of Command pattern?

A

1) Class which incapsulate action ( command )
2) Invoker which executes this action
3) Undo the execution

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

Can you provide example of Adapter pattern?

A
class Cat
  def meow
    p "Meow"
  end
end

cat = Cat.new
cat.meow

class Dog
  def gav
    p "Gav"
  end
end

dog = Dog.new
dog.gav

class CatAdapter
  attr_reader :cat
  def initialize(cat)
    @cat = cat
  end

def sound
cat.meow
end
end

class DogAdapter
  attr_reader :dog
  def initialize(dog)
    @dog = dog
  end

def sound
dog.gav
end
end

[CatAdapter.new(cat), DogAdapter.new(dog)].each { |animal| animal.sound }

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

What is Adapter pattern?

A

Adapter is a structural design pattern, which allows incompatible objects to collaborate.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

What are the key components of Adapter pattern?

A
  1. Object with an inappropriate interface
  2. Appropriate interface
  3. Adapter which returns an object with an appropriate interface
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

What is Facade pattern?

A

Facade is a structural design pattern that provides a simplified interface to a complex system of classes, objects and methods.
Facade defines a higher-level interface that makes the subsystem easier to use

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

Can you provide an example of Facade pattern?

A
def show
  @cats = Cat.names
  @dogs = Dog.names
  #...
  @animal_count = @cats + @dogs # + ..

@animal_uniq_count = 0 # comlex logic
end

class Facade
  def animal_count
    @cats = Cat.names
    @dogs = Dog.names
    #...
    @animal_count = @cats + @dogs # + ..
  end
end

Facade.new.animal_count

25
Q

What are the key komponent of Facade pattern?

A
# 1. difficult interface
# 2. Encapsulate this interface in something more simple
26
Q

What is Template Method pattern?

A

Template Method is a behavioral design pattern that allows you to defines a skeleton of an algorithm in a base class and let subclasses override the steps without changing the overall algorithm’s structure.

27
Q

Can you provide example of Template Method pattern?

A
cclass AnimalTemplate
  def test_animal
    sound
    eat
    run
  end
  def sound
  end
  def eat
  end

def run
end
end

class Cat < AnimalTemplate
def sound
‘Miow’
end

  # ...
end
28
Q

What are the key components of Template Method pattern?

A
  1. Add template_method with the algorithm
  2. Define the skeleton of the class and algorithm
  3. Create subclass and let override skeleton methods(steps)
29
Q

What is Iterator pattern?

A

Iterator is a behavioral design pattern that lets you goes through elements of a collection without using its underlying representation (list, stack, tree, etc.).

30
Q

Can you provide the example of Iterator pattern?

A
class ArrayIterator
  def initialize(array)
    @array = array
    @index = 0
  end

def item
@array[@index]
end

def next?
@array.size > @index
end

  def next_item
    @index += 1
    @array[@index]
  end
end

p ArrayIterator.new([1,2,3]).next?

class HashIterator
  def initialize(hash)
    @hash = hash
    @index = :a
  end

def item
@hash[@index]
end

def next?
@hash.size > @index
end

  def next_item
    @index = @index.next
    @hash[@index]
  end
end

p HashIterator.new({a: 123,b: 12, c: 232}).next_item

31
Q

What are the key elements of Iterator pattern?

A
  1. List of objects with diferent interface for iteration
  2. Single Interface to do it for every object
  3. Item, next_item, has_next? operations
32
Q

What is Composite design pattern?

A

Composite is a structural design pattern that allows composing objects into a tree-like structure and work with the it as if it was a singular object.

33
Q

Can you provide an example of Composite pattern?

A
class Leaf
  attr_accessor :name, :parent
  def initialize(name)
    @name = name
    @parent = parent
  end

def operation
self.name
end
end

class Composite < Leaf

def initialize(name)
super(name)
@children = []
end

def add(component)
@children &laquo_space;component
component.parent = self
end

  def remove(component)
    @children.delete(component)
    component.parent = nil
  end

def operation
results = []
@children.each { |child| results &laquo_space;child.operation }
“Branch #{self.name} - (#{results.join(‘+’)})”
end

end

class Animal < Composite; end
class Cat < Composite; end
class Dog < Composite; end
class BritishCat < Leaf; end
class EgyptCat < Leaf; end
animal = Animal.new('Sample')
cat = Cat.new('Mik')
dog = Dog.new('Gav')
british_cat = BritishCat.new('Brit')
egypt_cat = EgyptCat.new('Egyp')

cat. add(british_cat)
cat. add(egypt_cat)

animal. add(cat)
animal. add(dog)

p animal.operation

34
Q

What are the key element of Composite pattern?

A
  1. Leaf ( which has name, parent and operation method)

2. Composite ( many leaves which have children and methods add, remove and recursive operation)

35
Q

What is State pattern?

A

State is a behavioral design pattern that allows an object to change the behavior when its internal state changes.

36
Q

Can you provide the example of State pattern?

A
class Car
  def initialize
    @state = BrokenCarState.new(self)
  end

def repair_car
@state.repair_car
end

def broke_car
@state.broke_car
end

def update_state(state)
@state = state
end
end

class BrokenCarState
  def initialize(car)
    @car = car
  end

def repair_car
p ‘Switch to working state’
@car.update_state(WorkingCarState.new(@car))
end

def broke_car
p ‘Nothing hapens’
end
end

class WorkingCarState
  def initialize(car)
    @car = car
  end

def repair_car
p ‘Nothing hapens’
end

  def broke_car
    p 'Switch to broken state'
    @car.update_state(BrokenCarState.new(@car))
  end
end

car = Car.new

car. repair_car
car. broke_car

37
Q

What are the key components of State pattern?

A
  1. Main context ( object )
  2. Actions for this object
  3. Object states which represent in separated classes
  4. Each state has actions, has ability to change state and context in the constructor
38
Q

What is Proxy pattern?

A

Proxy is a structural design pattern that provides a placeholder for another object to control access to it.

39
Q

Can you provide an example of proxy pattern?

A
class Cat
  def meow
    p 'Meow'
  end
end
class ProxyCat
  def initialize(cat)
    @cat = cat
  end

def meow
@cat.meow if true
end
end

cat = Cat.new
ProxyCat.new(cat).meow

40
Q

What are the key elements of Proxy pattern?

A
# 1. Object with an action
# 2. Class which wraps this object and adds condition to check before running object action
41
Q

What is Prototype pattern?

A

Prototype is a creational design pattern that allows cloning objects, even complex ones, without coupling to their specific classes.

42
Q

Can you provide an example of PrototypePattern?

A
class Animal
  def hello
    p 'hello'
  end
end
class AnimalPrototype
  def self.copy(object)
    object.clone
  end
end

animal = Animal.new
animal_prototype = AnimalPrototype.copy(animal)
p animal_prototype.hello

43
Q

What are the key elements of prototype pattern?

A
  1. Object

2. Prototype class with method copy which returns a copy of object.

44
Q

What is Strategy pattern?

A

Strategy is a behavioral design pattern that turns a set of behaviors into objects and makes them interchangeable inside original context object.

45
Q

Can you provide an example of Strategy pattern?

A
class Car
  def initialize(strategy)
    @strategy = strategy
  end
  def go
    p 'ingine start'
    @strategy.drive
    p 'something else...'
  end
end 
class DriveStrategy
  def drive
    p 'Drive mood'
  end
end
class SportStrategy
  def drive
    p 'Sport mood'
  end
end

Car.new(DriveStrategy.new).go

46
Q

What are the key elements of Strategy pattern?

A
  1. Common behavior (algorithm)

2. Different behavior inside the common algorithm

47
Q

What is Builder pattern?

A

Builder is a creational design pattern, which allows constructing complex objects step by step.

48
Q

Can you provide an example of Builder pattern?

A

class Car
attr_accessor :color, :music, :engine, :gps
end

class CarBuilder
  def initialize(car)
    @car = car
  end
  def set_color
    @car.color = 'green'
  end
  def set_music
    @car.music = 'Sony'
  end
  def set_engine
    @car.engine = 'Ferrari'
  end
  def set_gps
    @car.gps = 'GPS'
  end

def get_car
@car
end
end

car_builder = CarBuilder.new(Car.new)
car_builder.set_music
car_builder.set_engine
car_builder.set_color

p car_builder.get_car.engine

49
Q

What are the key elements of Builder pattern?

A
  1. Base class with lots of properties

2. Builder Class which has lots of methods to set_up properties.

50
Q

What is Memento pattern?

A

Memento is a behavioral design pattern that allows making snapshots of an object’s state and restoring it in future. ( Allows versioning)

51
Q

Can you provide an example of Memento pattern?

A
class Car
  attr_accessor :color
  def initialize(color)
    @color = color
  end

def save
CarVersion.new(self)
end
end

class CarVersion
  attr_reader :color

def initialize(car)
@color = car.color
end
end

class VersionHistory
  attr_reader :versions

def initialize
@versions = []
end

def add(version)
@versions &laquo_space;version
end

def get_version(number)
@versions[number]
end
end

car = Car.new(‘green’)

versions = VersionHistory.new
versions.add car.save

car. color = ‘blue’
versions. add car.save

p versions.get_version(1).color

52
Q

What are the key elements of Memento pattern?

A
  1. Entity (can save version and rollback changes)
  2. Single version of the Entity
  3. Class for all versions of the entity
53
Q

What 3 kinds of patterns do you know?

A
  • Creational
  • Structural
  • Behavioral
54
Q

What is Bridge pattern?

A

Bridge is a structural design pattern that lets you split a large class or a set of closely related classes into two separate hierarchies—abstraction and implementation—which can be developed independently of each other.

( Something like DVD played is abstraction and cassettes are realizations )

55
Q

Can you provide an example of Bridge pattern?

A

Realization

# Interface
class RemoteControl
  def initialize(device)
    @device = device
  end
  def volume_down
    device.volume_down
  end

def volume_up
device.volume_up
end

private

attr_reader :device

end

class TV
  def volume_down
    p "TV volume down"
  end

def volume_up
p “TV volume up”
end
end

class Radio
  def volume_down
    p "Radio volume down"
  end

def volume_up
p “Radio volume up”
end
end

radio = Radio.new
tv = TV.new

RemoteControl.new(radio).volume_up
RemoteControl.new(tv).volume_up

56
Q

What are the key elements of Bridge?

A
  • Abstract class with an interface

- Realization which we send to the interface

57
Q

What is flyweight pattern?

A

Flyweight is a structural design pattern that lets you fit more objects into the available amount of RAM by sharing common parts of state between multiple objects instead of keeping all of the data in each object.

58
Q

What is chain of responsibilities pattern?

A

Chain of Responsibility is a behavioral design pattern that lets you pass requests along a chain of handlers. Upon receiving a request, each handler decides either to process the request or to pass it to the next handler in the chain.
( It’s like army when you have strict order of execution and you check who can do it)

59
Q

Can you provide an example of a chain of responsibility pattern?

A

class Handler

  def handle(number)
  end

def set_next(handler)
@next_handler = handler
end
end

class Solder < Handler
  def handle(number)
    if number > 5
      @next_handler.handle(number)
    else
      p "Solder #{number} handled"
    end
  end
end
class Capitan < Handler
  def handle(number)
    if number > 8
      @next_handler.handle(number)
    else
      p "Capitan #{number} handled"
    end
  end
end 
class General < Handler
  def handle(number)
    p "General #{number} handled"
  end
end
solder = Solder.new
capitan = Capitan.new
general = General.new

solder. set_next(capitan)
capitan. set_next(general)

solder.handle(10)