Wednesday, 6 March 2019

CommandPattern

CommandPattern


Cooming soon

AdapterPattern

AdapterPattern

                                 Intent

Convert the interface of a class into another interface clients expect. Adapter
lets classes work together that couldn't otherwise because of incompatible
interfaces.

                              Also Known As

Wrapper

                              Applicability

Use the Adapter pattern when

  • you want to use an existing class, and its interface does not match the one you need.
  • you want to create a reusable class that cooperates with unrelated or
    unforeseen classes, that is, classes that don't necessarily have compatible
    interfaces.
  • (object adapter only) you need to use several existing subclasses, but it's
    impractical to adapt their interface by subclassing every one. An object
    adapter can adapt the interface of its parent class.
     

                                  Structure



Class Diagram

Program


package AbstractFactory;

/**
 *
 * @author Sonu
 */
public interface SumsungMobile {

    String getMobile();
   

 ================Concrete Class for Creating the Mobile========

package AbstractFactory;

/**
 *
 * @author Sonu
 */
public class SumsungNote2 implements SumsungMobile{

    @Override
    public String getMobile() {
//        System.out.println("This is Sumsung Note2 Mobile.");
        return "This is Sumsung Note2 Mobile.";
    }
   

================Another concrete class for creating anther Mobile==
package AbstractFactory;

/**
 *
 * @author Sonu
 */
public class SumsungNote4 implements SumsungMobile{
    @Override
    public String getMobile() {
//        System.out.println("This is Sumsung Note4 Mobile.");
        return "This is Sumsung Note4 Mobile.";
    }
}

==========Another interface for creating anther product===========

package AbstractFactory;

/**
 *
 * @author Sonu
 */
public interface SumsungEarphone {
    String getEarphone();
}

============== Concrete class for creating  Earphone ===========

package AbstractFactory;

/**
 *
 * @author Sonu
 */
public class SumsungNote2 implements SumsungMobile{

    @Override
    public String getMobile() {
//        System.out.println("This is Sumsung Note2 Mobile.");
        return "This is Sumsung Note2 Mobile.";
    }
   
}

============Concrete class for creating  Earphone ==============

package AbstractFactory;
/**
 *
 * @author Sonu
 */
public class SumsungNote4EP implements SumsungEarphone{

    @Override
    public String getEarphone() {
//        System.out.println("This is Sumsung Note4  Earphone.");
        return "This is Sumsung Note4  Earphone.";
    }
   
}

 ============Creating factory class for product ================

package AbstractFactory;

import java.util.Scanner;

/**
 *
 * @author Sonu
 */
public class FactoryMobile extends AbstractFactory{
    @Override
    public SumsungEarphone getEarphone()
    {

       SumsungEarphone earphone=new SumsungNote2EP();
       return earphone;
    }

    @Override
    public SumsungMobile getMobile() {

        SumsungMobile sm=new SumsungNote2();
        return sm;
    }
}

================factory for creating another product===========

package AbstractFactory;
/**
 *
 * @author Sonu
 */
public class FactoryEarphone extends AbstractFactory{
    public SumsungMobile getMobile()
    {
        SumsungMobile sm=new SumsungNote4();
        return sm;
    }
    public SumsungEarphone getEarphone()
    {
        SumsungEarphone  earphone=new SumsungNote4EP();
        return earphone;
    }
}

=============Most IMP abstract factory ====================

package AbstractFactory;
/**
 *
 * @author Sonu
 */
public class FactoryEarphone extends AbstractFactory{
    public SumsungMobile getMobile()
    {
        SumsungMobile sm=new SumsungNote4();
        return sm;
    }
    public SumsungEarphone getEarphone()
    {
        SumsungEarphone  earphone=new SumsungNote4EP();
        return earphone;
    }
}

=================The main class =======================

package AbstractFactory;

import java.util.Scanner;

/**
 *
 * @author Sonu
 */
public class Main {
    public static void main(String[] args) {
        System.out.println("Enter Number 1 for Sumsung Note 2 Mobile and Earphone.");
        System.out.println("Enter Number 2 for Sumsung Note 4 Mobile and Earphone.");
        System.out.println("3 for note 5");
        Scanner s = new Scanner(System.in);
        int i = s.nextInt();
        AbstractFactory abstractFactory =AbstractFactory.getAbstractFactory(i);
        SumsungMobile sm = abstractFactory.getMobile();
        System.out.println(""+sm.getMobile());
        SumsungEarphone se = abstractFactory.getEarphone();
        System.out.println(""+se.getEarphone());
        //System.out.println(""+sm.getMobile());
   
    }
}

=================== output =========================

Output


 





Strategy Design Pattern

Intent

Define a family of algorithms, encapsulate each one, and make theminterchangeable.
Strategy lets the algorithm vary independently fromclients that use it.

Also Known As

Policy

Applicability

Use the Strategy pattern when
  • many related classes differ only in their behavior. Strategiesprovide a way to configure a class with one of many behaviors.
  • you need different variants of an algorithm. For example, you might definealgorithms reflecting different space/time trade-offs.Strategies can be used when these variants are implemented as a classhierarchy of algorithms 
  • an algorithm uses data that clients shouldn't know about. Use theStrategy pattern to avoid exposing complex, algorithm-specific datastructures.
  • a class defines many behaviors, and these appear as multipleconditional statements in its operations. Instead of manyconditionals, move related conditional branches into their ownStrategy class. 

Structure

 

Program

===================some title ========================

package Staragy;

/**
 *
 * @author Sonu
 */
public interface ISnak {
   
    public String snakeName();
}

====================some title =======================

package Staragy;

/**
 *
 * @author Sonu
 */
public interface ISnakeBehavior {
   
    public String behavior();
}

====================some title =======================

package Staragy;

/**
 *
 * @author Sonu
 */
public class NonPosinistion implements ISnakeBehavior{

    @Override
    public String behavior() {
       
        return "Non Position.";
    }
   
}

=====================some title ======================

package Staragy;

/**
 *
 * @author Sonu
 */
public class Posiginus implements ISnakeBehavior{

    @Override
    public String behavior() {
        return "Posigin.";
    }
   
}

========================some title ===================

package Staragy;

/**
 *
 * @author Sonu
 */
public class Contex {
   
    ISnak iSnak;
    ISnakeBehavior iSnakeBehavior;
    public Contex(ISnak iSnak , ISnakeBehavior iSnakeBehavior){
       
        this.iSnak = iSnak;
        this.iSnakeBehavior = iSnakeBehavior;
    }
   
    public String  setsnack()
    {
        return iSnak.snakeName() +"is"+ iSnakeBehavior.behavior();
    }
}

=====================some title ======================

package Staragy;

/**
 *
 * @author Sonu
 */
public class Ratsnak implements ISnak{

    @Override
    public String snakeName() {
        return "Rat Snak.";
    }
   
}

===================some title =======================

package Staragy;

/**
 *
 * @author Sonu
 */
public class Cobara implements ISnak{

    @Override
    public String snakeName() {
        return "Cobara";
    }
   
}

=====================The main class ===================

package Staragy;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 *
 * @author Sonu
 */
public class Main {
   
    public static void main(String[] args) throws IOException {
       
        Contex c1;
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("1.Cobara");
        System.out.println("2.RatSnack");
        int snack =Integer.parseInt(br.readLine());
        System.out.println("1.Posigon");
        System.out.println("2.Non-posion");
        int behavior = Integer.parseInt(br.readLine());
       
        if(snack == 1){
            if(behavior == 1)
            {
                c1 = new Contex(new Cobara(), new Posiginus());
                System.out.println(""+c1.setsnack());
            }
            else
            {
                c1 = new Contex(new Cobara(), new NonPosinistion());
                System.out.println(""+c1.setsnack());
            }
        }
        else if(snack == 2){
            if(behavior == 1){
                c1 = new Contex(new Cobara(), new Posiginus());
                System.out.println(""+c1.setsnack());
            }
            else
            {
                c1 = new Contex(new Cobara(), new NonPosinistion());
                System.out.println(""+c1.setsnack());
            }
        }
    }
}

=================output==============================


Decoretor Pattern

Intent

Attach additional responsibilities to an object dynamically. Decorators provide
a flexible alternative to subclassing for extending functionality.

                              Also Known As

Wrapper

                              Applicability

Use Decorator
                      
  •   to add responsibilities to individual objects dynamically and
    transparently, that is, without affecting other objects.
  •  for responsibilities that can be withdrawn.
  •  when extension by subclassing is impractical. Sometimes a large number of
    independent extensions are possible and would produce an explosion of
    subclasses to support every combination. Or a class definition may be hidden
    or otherwise unavailable for subclassing.

                                  Structure


Class Diagram

Program


 ====================Interface class=======================
package DecoratorPattern;

/**
 *
 * @author Sonu
 */
public interface IceCream {
   public double getCost();
   public String getDiscription();
}
==================== Abstract Class =======================

package DecoratorPattern;

/**
 *
 * @author Sonu
 */
public abstract class Decoretor implements IceCream{

    IceCream i;
    public Decoretor(IceCream i1) {
        i=i1;  
    }
   
    @Override
    public double getCost() {
        return i.getCost();
    }

    @Override
    public String getDiscription() {
        return i.getDiscription();
    }
   
}

================concreate class =======================

package DecoratorPattern;

/**
 *
 * @author Sonu
 */
public class Chocklate extends Decoretor{

    public Chocklate(IceCream i1) {
        super(i1);
    }
    public double getCost()
    {
        return super.getCost()+10;
    }
    public String getDiscription()
    {
        return super.getDiscription()+"With Chocklate";
    }
}

====================concreate class ====================

package DecoratorPattern;

/**
 *
 * @author Sonu
 */
public class Nutes extends Decoretor{

    public Nutes(IceCream i1) {
        super(i1);
    }
    @Override
    public double getCost()
    {
        return super.getCost()+20;
    }
    @Override
    public String getDiscription()
    {
        return super.getDiscription()+"With Nutes";
    }

}

=====================Concreate Class======================

package DecoratorPattern;

/**
 *
 * @author Sonu
 */
public class StrawbarryIceCream implements IceCream{

    @Override
    public double getCost() {
        return 15;
    }

    @Override
    public String getDiscription() {
        return "Add Strawbarry IceCream";
    }
   
}

===================Concreate Class========================

package DecoratorPattern;

/**
 *
 * @author Sonu
 */
public class VanillaIceCream implements IceCream{

    @Override
    public double getCost() {
     return 5.5;  
    }

    @Override
    public String getDiscription() {
        return "This is Vanilla IceCreame.";
    }
   
}

=================The main class =======================

package DecoratorPattern;

import java.util.Scanner;

/**
 *
 * @author Sonu
 */
public class Main {
    public static void main(String[] args) {
        System.out.println("Enter your Choise:");
        System.out.println("1.Vanilla IceCream.");
        System.out.println("2.Strawbarry IceCream");
        System.out.println("3.Vanilla IceCream with Chockalte.");
        System.out.println("4.Vanilla IceCream with Nutes.");
        System.out.println("5.Strawbarry IceCream with Chockalte.");
        System.out.println("6.Strawbarry IceCream with Nutes.");
        Scanner scanner = new Scanner(System.in);
        int i = scanner.nextInt();
        switch(i)
        {
            case 1:
                 IceCream ic = new VanillaIceCream();
                 System.out.println("Total Cost:"+ic.getCost());
                 System.out.println(""+ic.getDiscription());
                break;
            case 2:
                 ic = new StrawbarryIceCream();
                System.out.println("Total Cost:"+ic.getCost());
                System.out.println(""+ic.getDiscription());
                break;
            case 3:
                ic = new Chocklate((IceCream)new VanillaIceCream());
                System.out.println("Total Cost:"+ic.getCost());
                System.out.println(""+ic.getDiscription());
                break;
            case 4:
                ic = new Nutes((IceCream)new VanillaIceCream());
                System.out.println("Total Cost:"+ic.getCost());
                System.out.println(""+ic.getDiscription());
                break;
            case 5:
                ic = new Chocklate((IceCream)new StrawbarryIceCream());
                System.out.println("Total Cost:"+ic.getCost());
                System.out.println(""+ic.getDiscription());
                break;
            case 6:
                ic = new Nutes((IceCream)new StrawbarryIceCream());
                System.out.println("Total Cost:"+ic.getCost());
                System.out.println(""+ic.getDiscription());
                break;
                default:
                    System.out.println("You Chose Wrong Option.");
        }
    }
}

======================== output =====================

Output








Monday, 9 April 2018

Abstract Factory


                                 Intent

Provide a interface for creating families of related or depended object without specifying their concrete classes.

                              Also Known As

Kit

                              Applicability

Use the Abstract Factory when
                      
  •   A system should be independent of how its products are created,composed and represented.
  •   A system should be configured with one of multiple families of products.
  •  A family of related product objects is designed to be used together, and
    you need to enforce this constraint.
  • you want to provide a class library of products, and you want to reveal just their interfaces, not their implementations. 

                                  Structure


Class Diagram


Program


package AbstractFactory;

/**
 *
 * @author Sonu
 */
public interface SumsungMobile {

    String getMobile();
   

 ================Concrete Class for Creating the Mobile========

package AbstractFactory;

/**
 *
 * @author Sonu
 */
public class SumsungNote2 implements SumsungMobile{

    @Override
    public String getMobile() {
//        System.out.println("This is Sumsung Note2 Mobile.");
        return "This is Sumsung Note2 Mobile.";
    }
   

================Another concrete class for creating anther Mobile==
package AbstractFactory;

/**
 *
 * @author Sonu
 */
public class SumsungNote4 implements SumsungMobile{
    @Override
    public String getMobile() {
//        System.out.println("This is Sumsung Note4 Mobile.");
        return "This is Sumsung Note4 Mobile.";
    }
}

==========Another interface for creating anther product===========

package AbstractFactory;

/**
 *
 * @author Sonu
 */
public interface SumsungEarphone {
    String getEarphone();
}

============== Concrete class for creating  Earphone ===========

package AbstractFactory;

/**
 *
 * @author Sonu
 */
public class SumsungNote2 implements SumsungMobile{

    @Override
    public String getMobile() {
//        System.out.println("This is Sumsung Note2 Mobile.");
        return "This is Sumsung Note2 Mobile.";
    }
   
}

============Concrete class for creating  Earphone ==============

package AbstractFactory;
/**
 *
 * @author Sonu
 */
public class SumsungNote4EP implements SumsungEarphone{

    @Override
    public String getEarphone() {
//        System.out.println("This is Sumsung Note4  Earphone.");
        return "This is Sumsung Note4  Earphone.";
    }
   
}

 ============Creating factory class for product ================

package AbstractFactory;

import java.util.Scanner;

/**
 *
 * @author Sonu
 */
public class FactoryMobile extends AbstractFactory{
    @Override
    public SumsungEarphone getEarphone()
    {

       SumsungEarphone earphone=new SumsungNote2EP();
       return earphone;
    }

    @Override
    public SumsungMobile getMobile() {

        SumsungMobile sm=new SumsungNote2();
        return sm;
    }
}

================factory for creating another product===========

package AbstractFactory;
/**
 *
 * @author Sonu
 */
public class FactoryEarphone extends AbstractFactory{
    public SumsungMobile getMobile()
    {
        SumsungMobile sm=new SumsungNote4();
        return sm;
    }
    public SumsungEarphone getEarphone()
    {
        SumsungEarphone  earphone=new SumsungNote4EP();
        return earphone;
    }
}

=============Most IMP abstract factory ====================

package AbstractFactory;
/**
 *
 * @author Sonu
 */
public class FactoryEarphone extends AbstractFactory{
    public SumsungMobile getMobile()
    {
        SumsungMobile sm=new SumsungNote4();
        return sm;
    }
    public SumsungEarphone getEarphone()
    {
        SumsungEarphone  earphone=new SumsungNote4EP();
        return earphone;
    }
}

=================The main class =======================

package AbstractFactory;

import java.util.Scanner;

/**
 *
 * @author Sonu
 */
public class Main {
    public static void main(String[] args) {
        System.out.println("Enter Number 1 for Sumsung Note 2 Mobile and Earphone.");
        System.out.println("Enter Number 2 for Sumsung Note 4 Mobile and Earphone.");
        System.out.println("3 for note 5");
        Scanner s = new Scanner(System.in);
        int i = s.nextInt();
        AbstractFactory abstractFactory =AbstractFactory.getAbstractFactory(i);
        SumsungMobile sm = abstractFactory.getMobile();
        System.out.println(""+sm.getMobile());
        SumsungEarphone se = abstractFactory.getEarphone();
        System.out.println(""+se.getEarphone());
        //System.out.println(""+sm.getMobile());
   
    }
}

=================== output =========================

Output


 




Tuesday, 9 January 2018

Factory Method Design Pattern


Intent

Define an interface for creating an object, but let sub classes decide which class to instantiate. Factory Method lets a class defer instantiate to sub classes.

Also Known as

Virtual Constructor

                               Applicability

                                   Use the Factory Method pattern when

· a class can't anticipate the class of objects it must create.

· a class wants its sub classes to specify the objects it creates.

· classes delegate responsibility to one of several helper sub classes, and

you want to localize the knowledge of which helper subclass is the delegate.

                                         Structure



Participant

  

  Product (Document)

o defines the interface of objects the factory method creates.

· Concrete Product (My Document)

o implements the Product interface.

· Creator (Application)

o declares the factory method, which returns an object of type Product.
Creator may also define a default implementation of the factory
method that returns a default Concrete Product object.

o may call the factory method to create a Product object.

· Concrete Creator (My Application)

o overrides the factory method to return an instance of a
Concrete Product.

 Related Pattern

Abstract Factory.
Template.
Prototypes.

Class Diagram

Program

====================Interface for creating  product===========
package LangageCountry;

/**
 *
 * @author Sonu
 */
public interface Country {
    String  curruncy();
    String date();
    String percentage();
}


===================concrete class ====================

package LangageCountry;

import java.text.DateFormat;
import java.util.Currency;
import java.util.Date;
import java.util.Locale;
import javax.swing.JOptionPane;


/**
 *
 * @author Sonu
 */
public class INDIA implements Country{

    @Override
    public String curruncy()
    {  

          Currency c=Currency.getInstance(Locale.ITALY); // at this place you can use Locale.india
          return ""+c;
    }
    @Override
    public String date()
    {
        Date date = new Date();
         DateFormat df = DateFormat.getDateInstance(1,Locale.ITALY);
        String str= df.format(date);
          return ""+str;
    }

    @Override
    public String percentage() {
        return "percentage of india";
    }
}

====================Concrete class ====================

package LangageCountry;

import java.text.DateFormat;
import java.util.Currency;
import java.util.Date;
import java.util.Locale;
import javax.swing.JOptionPane;

/**
 *
 * @author Sonu
 */
 class JAPAN implements Country{

    @Override
    public String  curruncy() {
       
        Currency c = Currency.getInstance(Locale.JAPAN);
        return ""+c;
    }

    @Override
    public String date() {
       Date d = new Date();
        DateFormat df = DateFormat.getDateInstance(1,Locale.JAPAN);
        String str=df.format(d);
       return ""+str;
    }

    @Override
    public String percentage() {  
    return "Parcentage of japan";
    }
   
}

====================Concrete class ====================

package LangageCountry;

import java.text.DateFormat;
import java.time.Instant;
import java.util.Currency;
import java.util.Date;
import java.util.Locale;
import javax.swing.JOptionPane;

/**
 *
 * @author Sonu
 */
 class USA implements Country{
    @Override
    public String  curruncy() {
        Currency c = Currency.getInstance(Locale.US);
        return ""+c;
    }
    @Override
    public String  date() {
      
      Date date = new Date();
      DateFormat d=DateFormat.getDateInstance(1,Locale.US);
        String s=d.format(date);
        return ""+s;
    }

    @Override
    public String percentage() {
        return "Percentage of usa";
    }
}

=================The main class =======================

package LangageCountry;

import java.util.Scanner;


/**
 *
 * @author Sonu
 */
public class CreateCountry {
    public static void main(String []args)
    {
        System.out.println("Enter Number 1 for India");
        System.out.println("Enter Number 2 for Japan");
        System.out.println("Enter Number 3 for Usa");
        Scanner s = new Scanner(System.in);
        int i= s.nextInt();
        Country c = CountryFactory.getCountry(i);
        System.out.println("Curruncy : " + c.curruncy());
        System.out.println("Date : " + c.date());
        System.out.println("Precentage:"+c.percentage());
    }  
}

==================== output =========================

Output