• Thế Giới Giải Mã

    Bí ẩn nhân loại Leonardo Da Vinci

  • Thế Giới Giải Mã

    Anh hùng thầm lặng Nikola Tesla

  • Thế Giới Giải Mã

    Thần đèn Thomas Edison

  • Thế Giới Giải Mã

    Người thôi miên Adolf Hitler

Showing posts with label Design pattern. Show all posts
Showing posts with label Design pattern. Show all posts

15 August 2016

Strategy Design Pattern in Java

Step 1

Create an interface.
Strategy.java
public interface Strategy {
   public int doOperation(int num1, int num2);
}

Step 2

Create concrete classes implementing the same interface.
OperationAdd.java
public class OperationAdd implements Strategy{
   @Override
   public int doOperation(int num1, int num2) {
      return num1 + num2;
   }
}
OperationSubstract.java
public class OperationSubstract implements Strategy{
   @Override
   public int doOperation(int num1, int num2) {
      return num1 - num2;
   }
}
OperationMultiply.java
public class OperationMultiply implements Strategy{
   @Override
   public int doOperation(int num1, int num2) {
      return num1 * num2;
   }
}

Step 3

Create Context Class.
Context.java
public class Context {
   private Strategy strategy;

   public Context(Strategy strategy){
      this.strategy = strategy;
   }

   public int executeStrategy(int num1, int num2){
      return strategy.doOperation(num1, num2);
   }
}

Step 4

Use the Context to see change in behaviour when it changes its Strategy.
StrategyPatternDemo.java
public class StrategyPatternDemo {
   public static void main(String[] args) {
      Context context = new Context(new OperationAdd());  
      System.out.println("10 + 5 = " + context.executeStrategy(10, 5));

      context = new Context(new OperationSubstract());  
      System.out.println("10 - 5 = " + context.executeStrategy(10, 5));

      context = new Context(new OperationMultiply());  
      System.out.println("10 * 5 = " + context.executeStrategy(10, 5));
   }
}

Step 5

Verify the output.
10 + 5 = 15
10 - 5 = 5
10 * 5 = 50
Examp 2:
interface Strategy {
    public double getValue(double price);
}

class Add implements Strategy{
    @Override
    public double getValue(double price) {
        return price + 1.5;
    }
}

class Substract implements Strategy{
    @Override
    public double getValue(double price) {
        return price - 1.5;
    }
}

import java.util.ArrayList;
import java.util.List;

class Context {
   private List<Double> list;
   private Strategy strategy;
 
   public Context(Strategy strategy) {
        this.list = new ArrayList();
        this.strategy = strategy;
   }
   public void executeStrategy(double price, int Quantity) {
        list.add(strategy.getValue(price*Quantity));
   }
   public void displayPayment(){
        double sum =0;
        for(Double d : list){
           sum += d;
        }
        System.out.println("Total due: "+sum);
           list.clear();    
   }
}

class Program {

   public static void main(String[] args) {
        Context c = new Context(new Add());
        c.executeStrategy(9.5, 2);
        c.displayPayment();
     
        Context c1 = new Context(new Substract());
        c1.executeStrategy(9.5, 2);
        c1.displayPayment();
   }
}
Output: 
Total due: 20.5
Total due: 17.5

13 August 2016

Composite Design Pattern in Java


Composite pattern in UML.
import java.util.List;
import java.util.ArrayList;
 
//Component
interface Component {
    public void show();
}
 
//Composite
class Composite implements Component {
 
    private List<Component> childComponents = new ArrayList<Component>();
 
    public void add(Component component) {
     childComponents.add(component);
    }
 
    public void remove(Component component) {
     childComponents.remove(component);
    }
 
 @Override
 public void show() {
  for (Component component : childComponents) {
         component.show();
        }
 }
}
 
//leaf
class Leaf implements Component {
 String name;
 public Leaf(String s){
  name = s;
 }
    public void show() {
        System.out.println(name);
    }
}
 
 
public class CompositeTest {
 
    public static void main(String[] args) {
        Leaf leaf1 = new Leaf("1");
        Leaf leaf2 = new Leaf("2");
        Leaf leaf3 = new Leaf("3");
        Leaf leaf4 = new Leaf("4");
        Leaf leaf5 = new Leaf("5");
 
        Composite composite1 = new Composite();
        composite1.add(leaf1);
        composite1.add(leaf2);
 
        Composite composite2 = new Composite();        
        composite2.add(leaf3);
        composite2.add(leaf4);
        composite2.add(leaf5);
 
        composite1.add(composite2);
        composite1.show();
    }
}
Output: 
1
2
3
4
5

/** "Component" */
interface Shape{

    //Draw the color.
    public void draw(String fillColor);
}

/** "Composite" */
import java.util.List;
import java.util.ArrayList;
public class Drawing implements Shape{

 //collection of Shapes
 private List<Shape> shapes = new ArrayList<Shape>();
 
 @Override
 public void draw(String fillColor) {
  for(Shape sh : shapes)
  {
   sh.draw(fillColor);
  }
 }
 
 //adding shape to drawing
 public void add(Shape s){
  this.shapes.add(s);
 }
 
 //removing shape from drawing
 public void remove(Shape s){
  shapes.remove(s);
 }
 
 //removing all the shapes
 public void clear(){
  System.out.println("Clearing all the shapes from drawing");
  this.shapes.clear();
 }
}

/** "Triangle" */
public class Triangle implements Shape {

 @Override
 public void draw(String fillColor) {
  System.out.println("Drawing Triangle with color "+fillColor);
 }

}
/** "Circle" */
public class Circle implements Shape {

 @Override
 public void draw(String fillColor) {
  System.out.println("Drawing Circle with color "+fillColor);
 }

}


/** Client */
public class Program {

 public static void main(String[] args) {
  //Initialize four Triangle & Circle
  Shape tri = new Triangle();
  Shape tri1 = new Triangle();
  Shape cir = new Circle();
  //Initialize 1 composite drawing
  Drawing drawing = new Drawing();
  //Composes the drawing
  drawing.add(tri1);
  drawing.add(tri1);
  drawing.add(cir);
  
  drawing.draw("Red");
  
  drawing.clear();
  
  drawing.add(tri);
  drawing.add(cir);
  drawing.draw("Green");
 }

}
Output:
Drawing Triangle with color Red
Drawing Triangle with color Red
Drawing Circle with color Red
Clearing all the shapes from drawing
Drawing Triangle with color Green
Drawing Circle with color Green

12 August 2016

Private methods, Accessor Methods, Constant Data Manager Design Pattern in Java

Private methods Design Pattern
Java 2016
package Demo12;

public class Store {
 private int fx(int a, int b){
  return a*100 + b*20;
 }
 public void show(){
  System.out.println("Value fx(20,10): "+ fx(20,10));
  System.out.println("Value fx(40,10): "+ fx(40,10));
 }
 public static void main(String[] args) {
  Store s = new Store();
  s.show();
 }
}
/* 
Private tăng tính đóng gói cho Java như ví dụ này là tính đóng gói 
cho method fx(int a, int b) rằng private chỉ trong class Store 
mới có thể thấy nó và sử dụng nó! Xem lại phần tính đóng gói 
*/
Output: 
Value fx(20,10): 2200
Value fx(40,10): 4200
Accessor Methods Design Pattern
Java 2016
package Demo12;


public class Employee {

 private String name;
 private int salary;
 private int age;
 private String address;
 
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public int getSalary() {
  return salary;
 }
 public void setSalary(int salary) {
  this.salary = salary;
 }
 public int getAge() {
  return age;
 }
 public void setAge(int age) {
  this.age = age;
 }
 public String getAddress() {
  return address;
 }
 public void setAddress(String address) {
  this.address = address;
 }
}
/* Getter & Setter sinh ra nhằm mục đích tăng tính toàn vẹn tăng tính bảo mật ít lỗi 
Khi sử dụng chúng ta cần thông qua các method setName hoặc getName 
chứ không được truy cập trực tiếp ví dụ Employee.Name!
*/
Constant Data Design Pattern
Java 2016
package Demo12;

public class Constant {

 public static final String PROJECT ="JAVA TEAM 6";
 public static final String WEBSITE ="giai-ma.blogspot.com";
 public static final int YEAR = 2016;
 public static final String COUNSTRY ="Viet Nam";
}
/*
Có tác dụng nhóm các giá trị giống nhau vào một Class
Khi sử dụng chúng ta chỉ cần Constant.PROJECT thì lấy được giá trị 
*/

 

BACK TO TOP

Xuống cuối trang