OOP

Bowen
10 min readMar 23, 2021

This story is a part of — My CS Notebook

Themes

Inheritance Types

OOP supports Encapsulation; inheritance is a way for class first OOP languages to communicate and interact.

Single Inheritance

Multiple Inheritance

Multilevel Inheritance

Hierarchical Inheritance

Encapsulation

  • Encapsulation support modularity and is a pillar of computer sciences
  • Encapsulation is the process of wrapping code and data into a singular entity
  • Encapsulation allows for more complex structures
  • Encapsulation allows for more programmatic agility when accessing particular parts of the program, only the parts relevant to the task are in use
  • Encapsulation is often associated with “getters”, “setters”, “classes”, etc., but the principle can be found throughout Computer Sciences, for example, Dynamic Rendering, Imports / Exports, Libraries, Packages, Modules, Namespaces, etc.

Polymorphism

  • The idea that one thing can become another
Staic PolymorphismMethod Overloading: allows a client to implement the same class and same methods with different instantiation parameters. For example, a Coffee Machine class could have two constructor methods with two different method signatures: the first having just coffee selection, the second having coffee selection and quantityDynamic PolymorphismMethod Overriding: A Grand Parent, Parent, and Child could all share the same method with the same method signatures, however, a Parent could override a Grand Parent method to establish a different logic.

Delegation

  • Delegation is when you assign work to a different type. Delegation can be thought of as a type of inheritance, but it differs.

Example: Let say that you wanted to create a Java Application named “Jiffy Lube.” To create as close to a real-world example you would have to use a number of CS paradigms. One of those would be delegation.

You could rely solely on inheritance casting everything (Mechanism, Cashier, Tools, Property, Building, Inventory) under Type Resource). However, this would turn the task into a very difficult one. Delegation in CS would require you to separate types by category, have the building delegate repairs to the mechanics, have the mechanics delegate turning the work done into invoice to the cashiers, have the cashiers delegate the accounting to the accounts, have the accounts delegate the taxes to the government, have the government delegate the fees to the owner, have the owner delegate the expenses to the building, and so on.

Patterns

Creation Patterns

Singleton

§  Requirements:- Only one instance of the class is created- Must be able to access globally§  Examples:- One FS, One Logger, One Window Manager, etc.§  Implementation:- One Static Definition of Instance, one static “getter” method for retrieving the instance§  What is fixes:- Singletons and Factories - - If there are two identical factory instances, there is possibility for overlap, a singleton factory would prevent this

Factory

§  Requirements:- Creates object without exposing the instantiation logic- Allows all created objects to share a common interface§  Examples:- A graphical application would need a shape factory§  Implementations:- Factory produces product that have a shared interface- Factory implements instantiation logic with support encapsulation

Factory Method

§  Similar to Factory but with a little more abstraction

Abstract Factory

§  Similar to Factory Method but with even more abstraction

Factory, Factory Method, and Abstract Factory (Differences)

§  A Factory is “fixed”: if you wanted to create an “Apple” and an “Orange” from a “Fruit Factory”, you would use two separate methods “makeApple” and “makeOrange”§  A factory method is less fixed and can allow for “shared” generic processing before implementing a specific derived but unique subclass.- For example, if you wanted different types of Fruit to have a “shared” Picking Logic, you would implement “OrangePicker extends FruitPicker” & “ApplePicker extends FruitPicker”. OrangePicker would have specific instantiation logic to Oranges, and ApplePicker would have specific instantiation logic to Apples, but both would share the Logic associated with “FruitPicking”§  An abstract factory is like a Factory Interface.- For example, AppleFactory and OrangeFactory would both implement PlantFactory. AppleFactory and OrangeFactory would both have makePlant and makePicker methods, but the logic contained within the methods would be uniquie to both the AppleFactory and OrangeFactory

Builder

§  Builder is similar to a Factory but deviates in a couple ways:- Builder’s are more flexible and meant for a step by step process- The final stage of a builder is to return a finalized object, while a factory returns a finalized object immediately§  Example: If a GUI was made for Academia a Student and Teacher would have different features available, but the both would be of Type “user”. The GUI could use a Builder to “build” the available feature set for specific implementations of “user” subclasses

Prototype

§  Prototype clones a baseline structure for reuse by subclass implementations§  Prototype is similar to a “factory method”, but it is more flexible in that Factories tend to be more “Type Specific”§  Prototype can be analogous to a “survival kit” or “toolbox”, has base line features that classes can easily use.§  This support modularity and reusability.§  Implementation:- Prototype: Baseline Abstraction- ConcretePrototype: Cloned Implementation of Prototype- Client: Instantiated Concrete Prototype

Object Pool

§  Object instantiation can be expensive, Object Pools aim to make objects that are “expensive” to create reusable and shareable across clients§  An analogous example would be grocery store shelfing: there is a limited about of retail space, inventory comes and goes.

Behavioral Patterns

Chain of Responsibility

§  Real world example: A vending machine has one-coin slot (the sender) for every type of coin, (receiver) parse each coin and allocates it to the appropriate spot. This pattern avoids the need for having a different slot for each differing type of coin.§  Coding example: a request (sender) from a client to a server goes through a URL parser (receive) the URL parser dispatches (sender) to a API view (receiver)

Command

§  Declares and interface for executing an operation and is abstract§  Concrete Command is a implementation of a command with an execution method created by the (sender); Concrete Command encapsulates the “receiver” and when invoked tells the encapsulated “receiver” to carry out the action§  Distilled: command is a “container” to link receivers and actions

Interpreter

§  A “translation” design pattern§  Classic Example: Roman Numerals Convertor (input: string, output: integer)

Iterator

§  Most commonly attached to a “collection” – grouping of objects§  Use Case: Allows access to collection without exposing internal structure§  Example: linked-list§  Implementation: while iterating a linked-list a user must define a pointer to establish the current position. An iterator would provide two methods: hasNext and next. hasNext will tell the client where there is any forward movement left within the collection, next provides the next value in the collection§  Different Types of Iterators- Forward Iterators: provide begin, end, next, hasNext- Bidirectional Iterators: forward iterators but provide bidirectional navigation- Random-access iterators: Bidirectional iterators, but provide random access- Input Iterators: provide read-only access navigating forward- Output Iterators: provide write-only access while navigating forward

Mediator

§  In the example of OOP being a train, mediators would act as the couplers between cars (different from an explanation of linked lists)§  Mediators can help keep scaled structures “clean” by provide a interface for two “colleague” objects to communicate§  A concrete mediator implements the Mediator Interface§  Colleague Object keep references to the mediator implementations they are attached to.§  Example: Chatroom (Mediator) defines how two Participants  (Colleague Classes) communicate

Observer

§  Create a one-to-many relations between objects. When one object undergoes a state-change, all objects are notified.§  Examples:- Model – View – Contoller --- the view and model can become “decoupled” allowing the view to observer the observable (the model)- Events: An observer “watches” for changes in state of “observables”. “observables” in the case of a browser could be mouse click, key presses, mouse movement, etc.

Strategy

§  Strategy is similar to the Builder pattern with the exception of the fact that Builder is meant for Creation and Strategy is meant for action.§  Example: a battle bot has a number of functionalities. It needs to be able to act upon these functionalities with little effort. A strategy pattern would group all of its capabilities into one implementation for quick access.

Template Method

§  Template Method is similar to Prototype in that it gives a basic structure for reusability via encapsulation however it differs in the fact that template methods are used for actions and prototypes are used for creation.§  When filling out a job application, the form may change dynamically based on the input. A template method implementation would allow all of the variants to exist within a class without requiring that all be used.

Visitor

§  Visitor allows for unique, repeatable, and/or unrelated actions to be utilized by different types.§  Visitor is a way to support modularity and reusability across types§  Real World Example: In Sims there are characters and places. If a character visits a place like a museum Sims wants the user to be able to interact with the museum by open the door, but Sims does not want to open the museum door to be a part of the Character structure that travels throughout the rest of the world. In this example the Visitor Method allows a character object to utilize an “algorithmic” behavior without mutating the character object or otherwise requiring it to include the “algorithmic” behavior.

Null Object

§  Null object allows an object to exist without a specific definition.§  Null objects are often additive to Factory patterns, for example when a Concrete Implementation is created it must have a return value, if there is an instance in which the Object is not created by the Factory by design the default would be to return a Null Object to the requesting client

Structural Patterns

Adapter

§  Adapters are not too different from Mediators. They allow for “coupling” between objects, however they deviate in the sense that adapter are more useful for “coupling” objects with differing interfaces.§  Real-world example: a transform can be consider an adapter between a main power line and the power supply of a house§  “Wrappers” can be thought of as adapters in the sense that they take two things and combine them to accomplish a task. However the wrapper itself accomplishes nothing without both components, thus the adapter is simply a mechanism to utilized two or more resources for a specific task than no sole included resource could accomplish on its own.

Bridge

§  Sometimes abstractions need to be implemented in different ways. The goal of a bridge is to “decouple” the abstraction from the implementation§  A Mediator is essential an Adapter used as a Bridge. Interface M needs to work with Implementation A and Implementation B, both A and B have different implementations, therefore M cannot operate as an Interface for both A and B. When a “bridge is placed between” interface M and Implementations A and B, the bridge implements M allowing A and B to be related to M without having to be strictly M.

Composite

§  Composite structure allows uniform treatment across variable types§  For example: in a vector based shape program we might have the following- Interface Shape- Class Line impl. Shape, Class Rectangle impl. Shape (Leaf’s)- Class Dinosaur impl.  Shape- Client -> GUI§  In this example the Dinosaur would hold a collection of “leaf’s” and would have all of the base methods of Interface Shape. Class Dinosaur would be an example of a composite§  Composites can help group complex hierarchies into less complex “part-of-the-whole hierarchy” where multiple composites define the whole.§  A secondary example of this would be FileSystems. A folder might be a composite of resources, where Class Folder (Type Resource) holds many Class File (Type Resource).

Decorator

§  Add additional responsibilities to an object dynamically§  For example: let say that a car buyer is looking to buy a stock car and modify it on the aftermarket- Interface Component defines Car Operations and Attributes- Concreate Component creates Car- Decorator is a 3rd shop that adds nitrous to the fuel line and has a defined interface to “couple” the additive behavior to a base implementation of Component- Concrete Decorator – Implements Decorator, allowing the client to drive his car with the additive operation of nitrous

Flyweight

§  Flyweight is an interface that can be shared with a vast number of A Type objects that can receive and act on objects that are external to the initial object.§  Requirements:- Must define and maintain internal state- Must be able to mutate external states§  Example: In the popular title “Maneater” the protagonist is a shark that interacts in an Ocean. An Ocean contains a multitude of biodiversity and exponential amount of each particular type of biodiversity. In the game the protagonist can apply and receive damage from (boats, humans, tuna, barracuda, etc.). Each interactive and external object (boats, humans, tuna, barracuda, etc.) have their own intrinsic properties. The protagonists must be able to mutate the external objects, and the external objects must be able to mutate the protagonist. However, it would be a huge memory concern to have a one-to-one relationship for every interaction the protagonist has with an external object. A fly-weight pattern can reduce this expense by externalizing the state-mutations related to any action.§  Implementation:- Flyweight Interface- ConcreteFlyweight Impl. Flyweight- Flyweight Factory -> Collection of Flyweight§  Explanation: in “Maneater” the FlyWeight factory would receive a request from a client for an new external resource. If it exists the factory would return the existing object, if not it would create a new one. The health and location of the existing or new object would be reset, but the base object would not need to be recreated.

Memento

§  Memento captures the state of an existing object§  Examples:- History in a browser- Undo on a paint application- Snapshot in Jest Testing with React

Proxy

§  A placeholder§  Implementations: Placeholder object holds same interface as reference object§  Real world Example: Domain Name Server (DNS) holds list of domains, return associated IP

This story is a part of — My CS Notebook

Enjoy the read?

Leave a clap or comment

Share with friends or on your favorite social platform

--

--