Java
Shape interface:
public interface Shape {
public void draw();
}
Concrete Shape implementations:
public class Circle implements Shape {
@Override
public void draw() {
System.out.println("circle");
}
}
public class Square implements Shape {
@Override
public void draw() {
System.out.println("square");
}
}
Shape Factory:
public class ShapeFactory {
public Shape getShape(String shapeType){
if(shapeType.equals("circle")){
return new Circle();
} else if(shapeType.equals("square")){
return new Square();
}
return null;
}
}
Usage:
new ShapeFactory().getShape("circle").draw();
new ShapeFactory().getShape("square").draw();
Clojure
Shape interface:
(defprotocol Shape
"Shape inteface"
(draw [this]))
Concrete Shape implementations:
(deftype Circle []
Shape
(draw [this] "circle"))
(deftype Square []
Shape
(draw [this] "square"))
Shape Factory:
(defprotocol ShapesFactory
"Shapes Factory"
(getShape [this t]))
(deftype ShapeFactory []
ShapesFactory
(getShape [this t] (cond (= t "circle") (Circle.)
(= t "square") (Square.))))
Usage:
(draw (getShape (ShapeFactory.) "circle"))
(draw (getShape (ShapeFactory.) "square"))
Brak komentarzy:
Prześlij komentarz