Design Pattern: Factory Pattern

Factory Pattern is one of the most used design patterns in Java. It is an Creational Pattern, providing one of the best ways to create an object. The pattern enables the code to choose which implementation to call at run time based on arguments provided to the Factory. Thus helping to create generic and maintainable code. The pattern also allows the developer the ease of adding new types of implementations without changing the old code.

In Factory pattern, we create object without exposing the creation logic to the client and refer to newly created object using a common interface.

Implementation

The demo code shown below demonstrates Pizza variations and based on the argument type passed to it, the factory will return the type of Pizza requested for.

For demo purpose, the code only shows for Cheese, Veg and Fresh Pan Pizza only.

factory-pattern

Pros and Cons:

Pro’s:

  • Allows you to hide implementation of an application seam (the core interfaces that make up your application)
  • Allows you to easily test the seam of an application (that is to mock/stub) certain parts of your application so you can build and test the other parts
  • Allows you to change the design of your application more readily, this is known as loose coupling

Con’s

  • Makes code more difficult to read as all of your code is behind an abstraction that may in turn hide abstractions.
  • Can be classed as an anti-pattern when it is incorrectly used, for example some people use it to wire up a whole application when using an IOC container, instead use Dependency Injection.

HackerEarth: Battle Of Bots 6: Draughts

Problem:

Sample Game

Draughts is a two player board game which is played on a 8X8 grid of cells and is played on opposite sides of the game-board. Each player has an allocated color, Red ( First Player ) or White ( Second Player ) being conventional. Players take turns involving diagonal moves of uniform game pieces in the forward direction only and mandatory captures by jumping over opponent pieces.

Rules:

  • Player can only move diagonally to the adjacent cell and in forward direction, if the diagonally adjacent cell is vacant.
  • A player may not move an opponent’s piece.
  • If the diagonally adjacent cell contains an opponent’s piece, and the cell immediately beyond it is vacant, the opponent’s piece may be captured (and removed from the game) by jumping over it in the forward direction only.
  • If a player made a jump, then its mandatory to keep on jumping as long as the jump is possible.
  • Player cannot move to the diagonally adjacent cell once the player made a jump.

The game will end when any of the players don’t have any move left. At the end of the game the player with majority of pieces will win.

We will play it on an 8X8 grid. The top left of the grid is [0,0] and the bottom right is [7,7].

Input:
The input will be a 8X8 matrix consisting only of 0o2. Then another line will follow which will contain a number –  1 or 2 which is your player id. In the given matrix, top-left is [0,0] and bottom-right is [7,7]. The x-coordinate increases from left to right, and y-coordinate increases from top to bottom.

The cell marked 0 means it doesn’t contain any stones. The cell marked 1 means it contains first player’s stone which is Red in color. The cell marked 2 means it contains second player’s stone which is white in color.

Output:
In the first line print the coordinates of the cell separated by space, the piece he / she wants to move.
In second line print an integer N, number of steps or jumps the piece will make in one move.
In the next N lines print the coordinates of the cells in which the piece will make jump.
You must take care that you don’t print invalid coordinates. For example, [1,1] might be a valid coordinate in the game play if [1,1] in diagonal to the piece in which is going to jump, but [9,10] will never be. Also if you play an invalid move or your code exceeds the time/memory limit while determining the move, you lose the game.

Starting state
The starting state of the game is the state of the board before the game starts.

0 1 0 1 0 1 0 1
1 0 1 0 1 0 1 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 2 0 2 0 2 0 2
2 0 2 0 2 0 2 0

First Input
This is the input give to the first player at the start of the game.

0 1 0 1 0 1 0 1
1 0 1 0 1 0 1 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 2 0 2 0 2 0 2
2 0 2 0 2 0 2 0
1
SAMPLE INPUT
0 1 0 1 0 1 0 1
1 0 1 0 1 0 0 0
0 0 0 0 0 1 0 0
0 0 0 0 2 0 0 0
0 0 0 0 0 0 0 0
0 0 2 0 0 0 0 0
0 0 0 2 0 0 0 2
2 0 2 0 2 0 2 0
1
SAMPLE OUTPUT
2 5
2
4 3
6 1

Explanation

This is player 1’s turn, and the player will move the piece at [2,5] and will make two jumps. First jump will be at [4,3and second jump will be at [6,1]

After his/her move the state of game becomes:

0 1 0 1 0 1 0 1
1 0 1 0 1 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 1 0 2 0 2 0 2
2 0 2 0 2 0 2 0

This state will be fed as input to program of player 2.

Other valid move for the first player is

2 5
1
3 6

But the following are invalid moves.
Case 1:

2 5
1
4 3

Because after making a jump its possible to jump again and its mandatory to jump as long as its possible to jump.

Case 2:

2 5
2
4 3
5 4

Because after making a jump its invalid to move to diagonally adjacent cell.

Here is the code of the Random Bot.

Time Limit:1.0 sec(s) for each input file.
Memory Limit:256 MB
Source Limit:1024 KB

Solution

This is the solution submitted by me

System Design Interview Prep Material

System design is a very broad topic. Even a software engineer with many years of working experience at top IT company may not be an expert on system design. If you want to become an expert, you need to read many books, articles, and solve real large scale system design problems. This repository only teaches you to handle the system design interview with a systematic approach in a short time. You can dive into each topic if you have time. Of course, welcome to add your thoughts!

Table of Contents

System Design Interview Tips:

  • Clarify the constraints and identify the user cases Spend a few minutes questioning the interviewer and agreeing on the scope of the system. Remember to make sure you know all the requirements the interviewer didn’t tell your about in the beginning. User cases indicate the main functions of the system, and constraints list the scale of the system such as requests per second, requests types, data written per second, data read per second.
  • High-level architecture design Sketch the important components and the connections between them, but don’t go into some details. Usually, a scalable system includes web server (load balancer), service (service partition), database (master/slave database cluster plug cache).
  • Component design For each component, you need to write the specific APIs for each component. You may need to finish the detailed OOD design for a particular function. You may also need to design the database schema for the database.

Basic Knowledge about System Design:

Here are some articles about system design related topics.

Of course, if you want to dive into system related topics, here is a good collection of reading list about services-engineering, and a good collection of material about distributed systems.

Company Engineering Blogs:

If you are going to have an onsite with a company, you should read their engineering blog.

Products and Systems:

The following papers/articles/slides can help you to understand the general design idea of different real products and systems.

Hot Questions and Reference:

There are some good references for each question. The references here are slides and articles.
Design a CDN network Reference:

Design a Google document system Reference:

Design a random ID generation system Reference:

Design a key-value database Reference:

Design the Facebook news feed function Reference:

Design the Facebook timeline function Reference:

Design a function to return the top k requests during past time interval Reference:

Design an online multiplayer card game Reference:

Design a graph search function Reference:

Design a picture sharing system Reference:

Design a search engine Reference:

Design a recommendition system Reference:

Design a tinyurl system Reference:

Design a garbage collection system Reference:

Design a scalable web crawling system Reference:

Design the Facebook chat function Reference:

Design a trending topic system Reference:

Design a cache system Reference:

Good Books:

Object Oriented Design:

Tips for OOD Interview

Clarify the scenario, write out user cases Use case is a description of sequences of events that, taken together, lead to a system doing something useful. Who is going to use it and how they are going to use it. The system may be very simple or very complicated. Special system requirements such as multi-threading, read or write oriented.
Define objects Map identity to class: one scenario for one class, each core object in this scenario for one class. Consider the relationships among classes: certain class must have unique instance, one object has many other objects (composition), one object is another object (inheritance). Identify attributes for each class: change noun to variable and action to methods. Use design patterns such that it can be reused in multiple applications.

Useful Websites

Original Source

HackerRank: CodeWhiz.java March 2016: Java Singleton

Problem

“The singleton pattern is a design pattern that restricts the instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system.”
Wikipedia: Singleton Pattern


Complete the Singleton class in your editor which contains the following components:

  1. A private Singleton non parameterized constructor.
  2. A public String instance variable named strstr.
  3. Write a static method named getSingleInstance that returns the single instance of theSingleton class.

Once submitted, our hidden Solution class will check your code by taking a String as input and then using yourSingleton class to print a line.

Input Format

You will not be handling any input in this challenge.

Output Format

You will not be producing any output in this challenge.

Sample Input

hello world

Sample Output

Hello I am a singleton! Let me say hello world to you

Solution

Easy Rules: Java™ rules engine

Easy Rules is a Java rules engine inspired by an article called Should I use a Rules Engine? by Martin Fowler in which he says:

You can build a simple rules engine yourself. All you need is to create a bunch of objects with conditions and actions, store them in a collection, and run through them to evaluate the conditions and execute the actions.

Core features

  • Lightweight library and easy to learn API
  • POJO based development with annotation programming model
  • Useful abstractions to define business rules and apply them easily with Java
  • The ability to create composite rules from primitive ones
  • Dynamic rule configuration at runtime using JMX

Example

Hello World tutorial

This tutorial shows how to use Easy Rules in a very simple application. The goal is to ask the user if he is a friend of duke and says ‘Hello duke’s friend!’ only if he replies ‘yes’.

Based on this requirement, the rule is pretty straightforward :

  • The condition is that the user input must be equal to ‘yes’
  • The action is to say ‘Hello duke’s friend!’ to the user

First, let’s create a rule class:

@Rule(name = "Hello World rule",
    description = "Say Hello to duke's friends only")
public class HelloWorldRule {

    /**
     * The user input which represents the data
     * that the rule will operate on.
     */
    private String input;

    @Condition
    public boolean checkInput() {
        //The rule should be applied only if
        //the user's response is yes (duke friend)
        return input.equalsIgnoreCase("yes");
    }

    @Action
    public void sayHelloToDukeFriend() throws Exception {
        //When rule conditions are satisfied,
        //prints 'Hello duke's friend!' to the console
        System.out.println("Hello duke's friend!");
    }

    public void setInput(String input) {
        this.input = input;
    }

}

Then, we have to register an instance of this rule in a Easy Rules engine and launch the tutorial with the following class:

public class Launcher {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);
        System.out.println("Are you a friend of duke?[yes/no]:");
        String input = scanner.nextLine();

        /**
         * Declare the rule
         */
        HelloWorldRule helloWorldRule = new HelloWorldRule();

        /**
         * Set business data to operate on
         */
        helloWorldRule.setInput(input.trim());

        /**
         * Create a rules engine and register the business rule
         */
        RulesEngine rulesEngine = aNewRulesEngine().build();

        rulesEngine.registerRule(helloWorldRule);

        /**
         * Fire rules
         */
        rulesEngine.fireRules();

    }
}

You would get the following output:

Are you a friend of duke? [yes/no]:
yes
INFO: Rule 'Hello World rule' triggered.
Hello duke's friend!
INFO: Rule 'Hello World rule' performed successfully.

Source

How to use decorator pattern, when the class to decorate is final

I have an inbuilt class in java – String
Now I have made 3 classes

  1. AddHashCode
  2. ToLowerCase
  3. AddLength

I want to create a class, which has toString method overridden while selecting one or more of the above classes.

For example:
I want a class, which has toString method, which has the features of AddHashCode and ToLowerCase
or
I want a class, which has toString method, which has the features of all of the above classes.

So, lets do it with Decorator Pattern.

But the problem with Decorator Pattern is, that the classes you create must implement the String class…..But String class is final..
So I have tweaked the Decorator Design Pattern a bit, though it closely resembles the purpose of Decorator design pattern.

Create the following three classes

Class AddHashCode

public class AddHashCode {
private String t ;
public AddHashCode(String s)
{
t = s;
}
public String toString()
{
return t.toString() + ":" + t.hashCode();
}
}

Class ToLowerCase

public class ToLowerCase {
String ac;
public ToLowerCase(String ac)
{
this.ac = ac;
}
public String toString()
{
return ac.toString().toLowerCase();
}
}

Class AddLength

public class AddLength{
private String t ;
public AddLength(String s)
{
t = s;
}
public String toString()
{
return t.toString() + ":"+t.toString().length();
}
}

Use this as follows:

public class Main {
public static void main(String[] args)
{
ToLowerCase x = new ToLowerCase
(new AddHashCode
(new String("YOGESH").toString()).toString());
System.out.println(x.toString());
AddHashCode y = new AddHashCode
(new ToLowerCase
(new AddLength(new String("YOGESH").toString())
.toString())
.toString());
System.out.println(y.toString());
}
}

Real time examples of Design patterns being used by Java

I am very keen to learn what all design patterns are being used by java code.

So here I am going to list them one by one.. I’ll keep on updating this article as and when I learn more about design patterns…

To begin with.. Lets learn something about strategy design pattern.

Strategy Design Pattern Examples

  • There are common situations when classes differ only in their behavior. For this cases is a good idea to isolate the algorithms in separate classes in order to have the ability to select different algorithms at runtime.
    Intent
  • Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it.

You must have seen how we create threads in Java… We make a class implement Runnable and override its run method. And then use that class’s object as an argument to Thread class constructor.

class xx implements Runnable  
{
@Override
public void run()
{
System.out.println("Running xx thread...");
}
}
class MyThread extends Thread
{
@Override
public void run()
{
System.out.println("mythread");
}
}
public class Main
{
public static void main(String args[])
{
xx r = new xx();
// Encapsulate what varies.. Note that
// Here the behavior of the run method varies...
// That is why it has been moved out of the Thread class..
Thread t = new Thread(r);
// Now that we have overridden the run method of Runnable interface
// and passed the object of class implementing it to the constructor of
// Thread class...
// In this case, the run method of r object will get invoked
// by the start method.
t.start();

Thread s = new MyThread();
// As we have now overriden the method of the Thread
// class itself, the start method will invoke the overridden
// run method.
// Here polymorphysm is attained by inheritance and not by
// encapsulation.. This is a weaker strategy than the first one.
s.start();


}
}

Well, if you see the definition of run() method in Thread class I think you’ll agree to what I have tried to explain above… Here is the definition in Thread class

/**
* If this thread was constructed using a separate
* Runnable run object, then that
* Runnable object's run method is called;
* otherwise, this method does nothing and returns.
*


* Subclasses of Thread should override this method.
*
* @see #start()
* @see #stop()
* @see #Thread(ThreadGroup, Runnable, String)
*/
public void run()
{
if (target != null)
{
target.run();
}
}

And if you look at the second way of creating a Thread, i.e. extending a Thread class… In that case the start method just invokes the run method… And because we have overridden the run method of Thread class, the default implementation of Thread’s run method will not get invoked, instead the implementation that we have given in the child class will get invoked.

/**
* Causes this thread to begin execution; the Java Virtual Machine
* calls the run method of this thread.
*


* The result is that two threads are running concurrently: the
* current thread (which returns from the call to the
* start method) and the other thread (which executes its
* run method).
*


* It is never legal to start a thread more than once.
* In particular, a thread may not be restarted once it has completed
* execution.
*
* @exception IllegalThreadStateException if the thread was already
* started.
* @see #run()
* @see #stop()
*/
public synchronized void start()
{
.....
}

Collections.sort(myCollections, myComparator);

This is another example of strategy design pattern, which I can think of.. As we are passing the behavior of comparison at run-time.

Example of Decorator Pattern – LineNumberScanner

Create a LineNumberScanner like this

public class LineNumberScanner implements Iterator
{
Scanner sc;
int i = 1;
public LineNumberScanner(Scanner sc)
{
this.sc = sc;
}

public boolean hasNextLine() {
return sc.hasNextLine();
}

public String nextLine() {
String nextLine = sc.nextLine();
if(nextLine==null) return nextLine;
else
{
return (i++)+":"+nextLine;
}
}

@Override
public void remove() {
sc.remove();
}

@Override
public boolean hasNext() {
return sc.hasNext();
}

@Override
public String next() {
return sc.next();
}
public void close()
{
sc.close();
}
}

Use the code as follows

public static void main(String[] args) throws FileNotFoundException 
{
File file = new File("D:\Yogesh.txt");
FileInputStream fis = new FileInputStream(file);
Scanner sc = new Scanner(fis);
LineNumberScanner lineScanner = new LineNumberScanner(sc);
while(lineScanner.hasNextLine())
{
System.out.println(lineScanner.nextLine());
}
}

Example of Decorator Pattern – LineNumberReader

Create a LineNumberReader like this

public class LineNumberReader extends BufferedReader 
{
int lineNo = 1;
public LineNumberReader(Reader in)
{
super((BufferedReader)in);
}
public void close() throws IOException
{
in.close();
}
/*
* Add more responsibility of adding a line Number in the beginning
*/
@Override
public String readLine() throws IOException
{
String line = super.readLine();
if(line==null) return line;
line = lineNo + ":" + line;
lineNo++;
return line;
}

}

Use the code as follows

public static void main(String[] args) throws FileNotFoundException 
{
File file = new File("D:\Yogesh.txt");
BufferedReader bufr = new BufferedReader(new FileReader(file));
BufferedReader lnr = new LineNumberReader(bufr);
Scanner sc ;
String line = "";
try
{
line=lnr.readLine();
while(line!=null)
{
System.out.println(line);
line=lnr.readLine();
}
}
catch(Exception e)
{
e.printStackTrace();
}
}