這裏是我的代碼抽象工廠模式 - 右鍵的方式來實現它
public class FactoryPatternDemo {
public static void main(String[]args)
{
AbstractFactory shapeFactory=new ShapeFactory();
//tramite la fabbrica di figura geometrica disegno un rettangolo..
Shape shape1=shapeFactory.getShape("rEcTaNgLe");
shape1.draw();
System.out.println();
//..e un triangolo
Shape shape2=shapeFactory.getShape("triangle");
shape2.draw();
}
形狀廠:
public class ShapeFactory extends AbstractFactory{
public ShapeFactory(){
}
@Override
public Shape getShape(String shapeType)
{
if (shapeType==null)
return null;
if (shapeType.equalsIgnoreCase("RECTANGLE"))
return new Rectangle();
if (shapeType.equalsIgnoreCase("TRIANGLE"))
return new Triangle();
return null;
}
抽象工廠:
public abstract class AbstractFactory {
public abstract Shape getShape(String shapeType);}
摘要產品
public interface Shape {
void draw();}
混凝土製品#1
public class Rectangle implements Shape {
@Override
public void draw() {
for(int i=0; i<5; i++)
{
if(i==0 || i==4)
{
for(int j=0; j<10; j++)
{
System.out.print("*");
}
}
else
{
for(int j=0; j<10; j++)
{
if(j==0||j==9)
System.out.print("*");
else
System.out.print(" ");
}
}
System.out.print("\n");
}
}
我的問題是:這是爲了實現一個抽象工廠模式的正確方法?客戶應該只能看到FactoryPatternDemo類抽象的東西或接口,但此行的代碼:
AbstractFactory shapeFactory=new ShapeFactory();
顯示了一個具體的工廠的名稱。這是一個錯誤嗎?謝謝你們