jeudi 3 septembre 2015

java design pattern to use

This could be a duplicate question, i'm learning different patterns and trying to implement in my code.

This is an example i'm trying to understand which pattern to use, i think of using factory pattern this confuses me for a scenario. I have an interface Shape and implementation classes Rectangle and Square

Rectangle & Square class implements all the methods in the Shape interface. Now, I have a couple of get and set methods to the Square class. If i use the factory patter this way, I get exceptions

public class Square implements Shape {  
   public String getSomeField() {
     return
   }
   public void setSomeField() {
      //set something
   }
}

public class ShapeFactory {
   public static Shape getShape(String shape) {
      if(shape.equals("rectange") {
         return new Rectangle();
      } else {
         return new Square();
      }
   }    
}

I instantiate my Square class like this: Shape square = ShapeFactory.getShape("square");

Since i have methods setSomeField() and getSomeField(), i get exceptions

Questions:

  1. Do I need to use factory pattern here or any other pattern?

  2. Do I have to instantiate like this: Square square = (Square)ShapeFactory.getShape("square");

Aucun commentaire:

Enregistrer un commentaire