Design Patterns: Difference between Factory and Abstract Factory Patterns

Both the Abstract Factory and Factory design pattern are creational design pattern and use to decouple clients from creating objects they need, But there is a significant difference between Factory and Abstract Factory design patterns, Factory design pattern produces implementation of Products like Garment Factory produce different kinds of clothes, On the other hand, Abstract Factory design pattern adds another layer of abstraction over Factory Pattern and Abstract Factory implementation itself like the AbstractFactory will allow you to choose a particular Factory implementation based upon need which will then produce different kinds of products.

In short

1) Abstract Factory design pattern creates Factory

2) Factory design pattern creates Products

Read more: https://javarevisited.blogspot.com/2013/01/difference-between-factory-and-abstract-factory-design-pattern-java.html#ixzz7xNNgk9lb

Design Patterns : Behavioral

(Observe the Iterator Visit, Strategize, and act as Mediator to create Memories)

Observer Design Pattern (Behavioral):
Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.

Define an object that is the “keeper” of the data model and/or business logic (the Subject). Delegate all “view” functionality to decoupled and distinct Observer objects. Observers register themselves with the Subject as they are created. Whenever the Subject changes, it broadcasts to all registered Observers that it has changed.

Example:
1) The observer pattern is used in the model view controller (MVC) architectural pattern. In MVC the this pattern is used to decouple the model from the view. View represents the Observer and the model is the Observable object.
2) News Publishing:
http://www.oodesign.com/observer-pattern.html
3) In Yahoo, whenever state of user changes, all concerned properties are notified and action taken accordingly.

Iterator Design Pattern (Behavioral) :
A collection is just a grouping of some objects. They can have the same type or they can be all cast to a base type like object. A collection can be a list, an array, a tree and the examples can continue. But what is more important is that a collection should provide a way to access its elements without exposing its internal structure. We should have a mechanism to traverse in the same way a list or an array. It doesn’t matter how they are internally represented.

The idea of the iterator pattern is to take the responsibility of accessing and passing trough the objects of the collection and put it in the iterator object. The iterator object will maintain the state of the iteration, keeping track of the current item and having a way of identifying what elements are next to be iterated.

“An aggregate object such as a list should give you a way to access its elements without exposing its internal structure. Moreover, you might want to traverse the list in different ways, depending on what you need to accomplish. But you probably don’t want to bloat the List interface with operations for different traversals, even if you could anticipate the ones you’ll require. You might also need to have more than one traversal pending on the same list.” And, providing a uniform interface for traversing many types of aggregate objects (i.e. polymorphic iteration) might be valuable.

The Iterator pattern lets you do all this. The key idea is to take the responsibility for access and traversal out of the aggregate object and put it into an Iterator object that defines a standard traversal protocol.

Example:
1) Book Collection: (uses “nested class”)
http://www.oodesign.com/iterator-pattern.html

Visitor Design Pattern (Behavioral) :
Represents an operation to be performed on a set of objects in a collection. Visitor lets you define a new operation without changing the classes of the elements on which it operates.

Example:
1) taxi example, where the customer calls orders a taxi, which arrives at his door. Once the person sits in, the visiting taxi is in control of the transport for that person.

2) Shopping in the supermarket is another common example, where the shopping cart is your set of elements. When you get to the checkout, the cashier acts as a visitor, taking the disparate set of elements (your shopping), some with prices and others that need to be weighed, in order to provide you with a total.

3) Postage Visitor applied to elements in a shopping cart:
http://java.dzone.com/articles/design-patterns-visitor

Main Class will implement a accept() method. example Book class will implement accept() method which will accept a visitor. PostageVisitor class will implement a visit method which will do the calculation.

public void accept(Visitor vistor) {
   visitor.visit(this);
}

Strategy Design Pattern:
The Strategy pattern provides a way to define a family of algorithms, encapsulate each one as an object, and make them interchangeable. A good use of the Strategy pattern would be saving files in different formats, running various sorting algorithms, or file compression

Memento Design Pattern:
Memento pattern which is used in undo frameworks to bring an object back to a previous state

Mediator:
An airport control tower is an excellent example of the mediator pattern. The tower looks after who can take off and land – all communications are done from the airplane to control tower, rather than having plane-to-plane communication. This idea of a central controller is one of the key aspects to the mediator pattern.

Design Patterns : Structural

(Adapt Face for Decoration and cross a Bridge with help of Proxy)

Adapter Design Pattern (Structural) :
Convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn’t otherwise because of incompatible interfaces.
Wrap an existing class with a new interface.
Impedance match an old component to a new system

Example: Adapter for electronic devices

Facade Design Pattern (Structural):
Provide a unified interface to a set of interfaces in a subsystem. Facade defines a higher-level interface that makes the subsystem easier to use.
Wrap a complicated subsystem with a simpler interface.

Example: Consumers encounter a Facade when ordering from a catalog. The consumer calls one number and speaks with a customer service representative. The customer service representative acts as a Facade, providing an interface to the order fulfillment department, the billing department, and the shipping department.

Decorator Design Pattern (Structural)

:
Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality. Add behavior or state to individual objects at run-time. Note that this pattern allows responsibilities to be added to an object, not methods to an object’s interface.

Example: Attaching a standard disclaimer signature to an email. (signature is the decorator)
http://java.dzone.com/articles/design-patterns-decorator

Example: assault gun is a deadly weapon on it’s own. But you can apply certain “decorations” to make it more accurate, silent and devastating.

Bridge Design Pattern:
Decouple an abstraction from its implementation so that the two can vary independently

Example of Blog and Themes
https://simpleprogrammer.com/2015/06/08/design-patterns-simplified-the-bridge-pattern/

Example of TV Remote, and TV implementors like Sony, Philips, etc.
http://java.dzone.com/articles/design-patterns-bridge

Proxy Pattern:
is very similar to the Adapter pattern. However, the main difference between bot is that the adapter will expose a different interface to allow interoperability. The Proxy exposes the same interface, but gets in the way to save processing time or memory. Typically, you’ll want to use a proxy when communication with a third party is an expensive operation, perhaps over a network. The proxy would allow you to hold your data until you are ready to commit, and can limit the amount of times that the communication is called.

Design Patterns : Creational

(Single Factory Builds Prototypes)

Singleton Pattern (Creational) :
Ensure a class has only one instance, and provide a global point of access to it.
Encapsulated “just-in-time initialization” or “initialization on first use”.

Example: The office of the President of the United States is a Singleton.
Example: Logger Class, Configuration Class
Reference: http://www.oodesign.com/singleton-pattern.html

Factory Pattern (Creational) :
– (Similar to Abstract Factory Pattern)
– One of the most used patterns in programming
– Define an interface for creating an object, but let subclasses decide which class to instantiate (usually with the help of a type parameter). Factory Method lets a class defer instantiation to subclasses.Defining a “virtual” constructor.
– creates objects without exposing the instantiation logic to the client. and refers to the newly created object through a common interface

Example:
For example a graphical application works with shapes. In our implementation the drawing framework is the client and the shapes are the products. All the shapes are derived from an abstract shape class (or interface). The Shape class defines the draw and move operations which must be implemented by the concrete shapes. Let’s assume a command is selected from the menu to create a new Circle. The framework receives the shape type as a string parameter, it asks the factory to create a new shape sending the parameter received from menu. The factory creates a new circle and returns it to the framework, casted to an abstract shape. Then the framework uses the object as casted to the abstract class without being aware of the concrete object type.

Example: Injection molding presses demonstrate this pattern. Manufacturers of plastic toys process plastic molding powder, and inject the plastic into molds of the desired shapes. The class of toy (car, action figure, etc.) is determined by the mold.

http://www.oodesign.com/factory-pattern.html

Builder Design Pattern (Creational) :
Builder is a creational design pattern that lets you construct complex objects step by step. The pattern allows you to produce different types and representations of an object using the same construction code. Separate the construction of a complex object from its representation so that the same construction process can create different representations.Parse a complex representation, create one of several targets. It is a mechanism for building complex objects that is independent from the ones that make up the object.

The “director” invokes “builder” services as it interprets the external format. The “builder” creates part of the complex object each time it is called and maintains all intermediate state. When the product is finished, the client retrieves the result from the “builder”.

Example: This pattern is used by fast food restaurants to construct children’s meals. Children’s meals typically consist of a main item, a side item, a drink, and a toy (e.g., a hamburger, fries, Coke, and toy dinosaur). Note that there can be variation in the content of the children’s meal, but the construction process is the same. Whether a customer orders a hamburger, cheeseburger, or chicken, the process is the same. The employee at the counter directs the crew to assemble a main item, side item, and toy.

http://www.oodesign.com/builder-pattern.html

The Builder design pattern is very similar, at some extent, to the Abstract Factory pattern. That?s why it is important to be able to make the difference between the situations when one or the other is used. In the case of the Abstract Factory, the client uses the factory?s methods to create its own objects. In the Builder?s case, the Builder class is instructed on how to create the object and then it is asked for it, but the way that the class is put together is up to the Builder class, this detail making the difference between the two patterns.

Prototype Pattern:
Prototype pattern refers to creating duplicate object while keeping performance in mind. This pattern involves implementing a prototype interface which tells to create a clone of the current object. This pattern is used when creation of object directly is costly. For example, a object is to be created after a costly database operation. We can cache the object, returns its clone on next request and update the database as as and when needed thus reducing database calls.

Infogain Questions

1) Given some text find all valid email addresses in it.

$ret = array();

function isValidEmail($word) {
$domain_parts = array();
$domain = "";

$components = explode("@", $word);

if (count($components) != 2) {
return false;
} else {
$domain = $components[1];
$domain_parts = explode(".", $domain);
if (count($domain_parts) < 2) {
return false;
}
}
return true;
}

function findEmailAddresses($input) {
$result = array();
if ((!$input) || empty($input)) {
return $result;
}
$words = explode(" ", $input);
foreach ($words as $word) {
if (isValidEmail($word)) {
$result[] = $word;
}
}
return $result;
}

$str = "This valid@email.com is just a test abc@ when @pqr is abc@pqr.com.";
$ret = findEmailAddresses($str);

var_dump($ret);

2) Given some text and an array of keywords, find all the words in the text which are any combination of the keywords. The below is by sorting. But another way is by hashing the keyword.

<?php

$ret = array();

function mysort($str) {
$arr = str_split($str);
sort($arr, SORT_STRING);
return implode("",$arr);
}

function findCombinations($input, $keywords) {
$result = array();
if ((!$input) || empty($input)) {
return count($result);
}
foreach ($keywords as $keyword) {
$sortedKeywords[] = mysort($keyword);
}
var_dump($sortedKeywords);
$inputArr = explode(" ", $input);
foreach ($inputArr as $word) {
$sortedInput[] = mysort($word);
}
var_dump($sortedInput);
foreach ($sortedInput as $sortedWord) {
if (in_array($sortedWord, $sortedKeywords)) {
$result[] = $sortedWord;
}
}
return $result;

}

$str = "This valid@email.com the is eht just a test abc@ when @pqr is abc@pqr.com.";
$keywords = array("het", "opo");
$ret = findCombinations($str, $keywords);

var_dump($ret);
?>

Promise

A promise is a JavaScript object that allows you to make asynchronous (aka async) calls. It produces a value when the async operation completes successfully or produces an error if it doesn’t complete. A promise may be in one of 3 possible states: fulfilled, rejected, or pending.

let myPromise = new Promise(function(myResolve, myReject) {
// "Producing Code" (May take some time)

myResolve(); // when successful
myReject(); // when error
});

// "Consuming Code" (Must wait for a fulfilled Promise)
myPromise.then(
function(value) { /* code if successful */ },
function(error) { /* code if some error */ }
)

 

  1. A “producing code” that does something and takes time. For instance, some code that loads the data over a network.
  2. A “consuming code” that wants the result of the “producing code” once it’s ready. Many functions may need that result.
  3. A promise is a special JavaScript object that links the “producing code” and the “consuming code” together. The “producing code” takes whatever time it needs to produce the promised result, and the “promise” makes that result available to all of the subscribed code when it’s ready.

React: Lifecycle of Components

Every React Component has a lifecycle of its own, lifecycle of a component can be defined as the series of methods that are invoked in different stages of the component’s existence.  A React Component can go through four stages of its life as follows.

  • Initialization: This is the stage where the component is constructed with the given Props and default state. This is done in the constructor of a Component Class.
  • Mounting: Mounting is the stage of rendering the JSX returned by the render method itself.
  • Updating: Updating is the stage when the state of a component is updated and the application is repainted.
  • Unmounting: As the name suggests Unmounting is the final step of the component lifecycle where the component is removed from the page.

Mounting:  componentWillMount() ==> render() ==> componentDidMount()

Updating:

componentWillReceiveProps() / setState() –>

shouldComponentUpdate() –> componentWillUpdate() –> render() –> componentDidUpdate()

UnMounting:

componentWillUnmount()