package com.andyidea.patterns.product;
/**
* Product: 需要创建的产品的抽象类.
* @author Andy.Chen
*
*/
public abstract class Shape {
public String name;
public Shape(String aName){
this.name = aName;
}
//绘画
public abstract void draw();
//擦除
public abstract void erase();
}
3.2 定义 Shape的两个子类: Circle, Square,实现Shape中定义的抽象方法
Circle中的源码如下:
package com.andyidea.patterns.concreteproduct;
import com.andyidea.patterns.product.Shape;
/**
* 圆形子类(ConcreteProduct: Product的子类,一系列具体的产品.)
* @author Andy.Chen
*
*/
public class Circle extends Shape{
public Circle(String name) {
super(name);
}
@Override
public void draw() {
System.out.println("It will draw a Circle");
}
@Override
public void erase() {
System.out.println("It will erase a Circle");
}
}
Square中的源码:
package com.andyidea.patterns.concreteproduct;
import com.andyidea.patterns.product.Shape;
/**
* 方形子类(ConcreteProduct: Product的子类,一系列具体的产品.)
* @author Andy.Chen
*
*/
public class Square extends Shape{
public Square(String name) {
super(name);
}
@Override
public void draw() {
System.out.println("It will draw a Square");
}
@Override
public void erase() {
System.out.println("It will erase a Square");
}
}
package com.andyidea.patterns.client;
import com.andyidea.patterns.concretecreator.CircleFactory;
import com.andyidea.patterns.concretecreator.SquareFactory;
import com.andyidea.patterns.creator.ShapeFactory;
/**
* 测试设计模式类
* @author Andy.Chen
*
*/
public class MainClient {
public static void main(String[] args) {
ShapeFactory sf1 = new CircleFactory();
ShapeFactory sf2 = new SquareFactory();
System.out.println("Welcome to Andy.Chen Blog!" +"\n"
+"Factory Method Patterns." +"\n"
+"-------------------------------");
sf1.anOperation("Shape-Circle");
sf2.anOperation("Shape-Square");
}
}
【4】程序运行结果如下:
Welcome to Andy.Chen Blog!
Factory Method Patterns.
-------------------------------
The current shape is: Shape-Circle (created by CircleFactory)
It will draw a Circle
It will erase a Circle
The current shape is: Shape-Square (created by SquareFactory)
It will draw a Square
It will erase a Square