interface Shape{
public void draw();
}
class Rectangle implements Shape{
public void draw(){
System.out.println("Rectangle implements Shape");
}
}
class Square implements Shape{
public void draw(){
System.out.println("Square implements Shape");
}
}
class Circle implements Shape{
public void draw(){
System.out.println("Circle implements Shape");
}
}
class ShapeFactory{
static Shape getShape(String shapeName){
if(null == shapeName){
return null;
}
if("Rectangle".equals(shapeName)){
return new Rectangle();
}else if("Square".equals(shapeName)){
return new Square();
}else{
return new Circle();
}
}
}
interface ShapeFactoryI{
public Shape getShapeFactoryDetail();
}
class RectangleFactory implements ShapeFactoryI{
public Shape getShapeFactoryDetail(){
return new Rectangle();
}
}
class SquareFactory implements ShapeFactoryI{
public Shape getShapeFactoryDetail(){
return new Square();
}
}
class CircleFactory implements ShapeFactoryI{
public Shape getShapeFactoryDetail(){
return new Circle();
}
}
* 1、 定义两个产品接口
* 2、 定义具体产品
* 3、 定义抽象工厂
* 4、 定义具体工厂
*/
* 1、创建产品1接口(上面的Shape接口)
* 创建产品2接口(这里的Color接口)
*/
interface Color{
public void getColor();
}
* 2、创建具体产品并实现产品1接口(上面的Shape接口)
* 创建具体产品并实现产品2接口(这里的Color接口)
*/
class Red implements Color{
public void getColor(){
System.out.println("Red implements Color");
}
}
class Green implements Color{
public void getColor(){
System.out.println("Green implements Color");
}
}
class Black implements Color{
public void getColor(){
System.out.println("Black implements Color");
}
}
* 3、定义抽象工厂
*/
interface AbstractFactory{
public Color getColorDetail();
public Shape getShapeDetail();
}
* 4、定义具体工厂
*/
class GreenSquareFactory implements AbstractFactory{
public Color getColorDetail(){
return new Green();
}
public Shape getShapeDetail(){
return new Square();
}
}
public class MainTest{
public static void main(String[] args){
System.out.println("simple factory TEST");
Rectangle rectangle = (Rectangle)ShapeFactory.getShape("Rectangle");
rectangle.draw();
System.out.println("\nfactory pattern TEST");
ShapeFactoryI shapeFactory = new CircleFactory();
Circle circle = (Circle)shapeFactory.getShapeFactoryDetail();
circle.draw();
System.out.println("\nabstract factory TEST");
AbstractFactory abstractFactory = new GreenSquareFactory();
abstractFactory.getColorDetail().getColor();
abstractFactory.getShapeDetail().draw();
}
}