TobNil

Factory Design Pattern

Mar 30th, 2016
47
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.83 KB | None | 0 0
  1. Main.Java
  2.  
  3. public class Main {
  4.  
  5.     public static void main(String[] args) {
  6.         ShapeFactory shapeFactory = new ShapeFactory();
  7.  
  8.         Shape shape1 = shapeFactory.getShape("TRIANGLE");
  9.         shape1.draw();
  10.  
  11.         Shape shape2 = shapeFactory.getShape("RECTANGLE");
  12.         shape2.draw();
  13.  
  14.         Shape shape3 = shapeFactory.getShape("SQUARE");
  15.         shape3.draw();
  16.     }
  17.  
  18. }
  19.  
  20. ===============================================================================================================
  21. ShapeFactory.Java
  22.  
  23. public class ShapeFactory {
  24.     public Shape getShape(String shapeType){
  25.         if(shapeType == null){
  26.             return null;
  27.         }
  28.         else if(shapeType.equalsIgnoreCase("RECTANGLE")){
  29.             return new Rectangle();
  30.         }
  31.         else if(shapeType.equalsIgnoreCase("SQUARE")){
  32.             return new Square();
  33.         }
  34.         else if(shapeType.equalsIgnoreCase("TRIANGLE")){
  35.             return new Triangle();
  36.         }
  37.        
  38.         return null;
  39.     }
  40. }
  41.  
  42. ===============================================================================================================
  43. Triangle.Java
  44.  
  45. public class Triangle implements Shape{
  46.  
  47.     @Override
  48.     public void draw() {
  49.         System.out.println("This is draw in Triangle");
  50.     }
  51.  
  52. }
  53.  
  54. ===============================================================================================================
  55. Square.Java
  56.  
  57. public class Square implements Shape{
  58.  
  59.     @Override
  60.     public void draw() {
  61.         System.out.println("This is draw in Sqaure");
  62.     }
  63.  
  64. }
  65.  
  66. ===============================================================================================================
  67. Rectangle.Java
  68.  
  69. public class Rectangle implements Shape{
  70.  
  71.     @Override
  72.     public void draw() {
  73.         System.out.println("This is draw from Rectangle");
  74.     }
  75.  
  76. }
  77.  
  78. ===============================================================================================================
  79. Shape.Java
  80.  
  81. public interface Shape {
  82.     public void draw();
  83. }
Add Comment
Please, Sign In to add comment