2.抽象工厂模式 和 工厂模式对比
简单来说,抽象工厂模式正如名字所示,即对工厂进行抽象,比起工厂模式多了一层抽象而已。在《Design Pattern Explains》书中,作者说的很到位,设计模式即是“Find what varies and encapsulate it”, 翻译过来即 封装起那些变换的事物。
如下所示(图引用于here):抽象工厂模式中把 产生A,B的工厂,抽象成一个 类,类中通过方法来产生有关联的产品,比如圆形,方形。而每个方法,都是依赖工厂模式实现
CODE 1: Factory Pattern
public interface Shape{
void draw();
}
public class Rectangle implements Shape{
public void draw(){
System.out.println("Inside Square::draw() method.");
}
}
public class CircleimplementsShape{
public void draw(){
Systerm.out.println("Inside Circle::draw() method");
}
}
public class ShapeFactory{
public shape getShape (String shapeType){
if(shapeType == null){
return null;
}
if(shapeType.equalsIgnoreCase("CIRCLE")){
return new Circle();
}else if(ShapeType.equalsIgnoreCase("RECTANGLE")){
return new Rectangle();
}else if(ShapeType.equalsIgnoreCase("SQUARE")){
return new Square();
}
return null;
}
}
// client code
public class FactoryPatternDemo{
public static void main(String[] args){
ShapeFactory shapeFactory = new ShapeFactory();
Shape shape1 = shapeFactory.getShape("CIRCLE");
shape1.draw();
Shape shape2 = shapeFactory.getShape("RECTANGLE");
shape2.draw();
Shape shape3 = shapeFactory.getShape("SQUARE");
shape3.draw();
}
}
CODE2: ABSTRACT Fatory PAttern
public interface Shape{
void draw();
}
public class Rectangle implements Shape{
public void draw(){
System.out.println("Inside Square::draw() method.");
}
}
public class Circle implements Shape{
public void draw(){
Systerm.out.println("Inside Circle::draw() method");
}
}
public interface <span style="color:#cc0000;">Color</span>{
void draw();
}
public class Red implements Color{
public void draw(){
System.out.println("Inside Red::fill() method.");
}
}
public class Green implements Color{
public void draw(){
Systerm.out.println("Inside Green::fill() method");
}
}
public abstract class AbstractFactory{
abstract Color getColor(String color);
abstract Shape getShape(String shape);
}
public class ShapeFactory extends AbstractFactory{
public shape getShape(String shapeType){
if(shapeType == null){
return null;
}
if(shapeType.equalsIgnoreCase("CIRCLE")){
return new Circle();
}else if(ShapeType.equalsIgnoreCase("RECTANGLE")){
return new Rectangle();
}else if(ShapeType.equalsIgnoreCase("SQUARE")){
return new Square();
}
return null;
}
// override
Color getColor(String color){
return null;
}
}
public class ColorFactory extends AbstractFactory{
//override
public Shape getShape(String shapeType){
return null;
}
Color getColor(String color){
if(color == null){
return null;
}
if(color.equalsIgnoreCase("RED")){
return new Red();
}else if(color.equalsIgnoreCase("Green")){
return new Green();
}
}
}
public class FactoryProducer{
public static AbstractFactory getFactory(String chioce){
if(choice.equalsIgnoreCase("SHAPE")){
return new ShapeFactory();
}else if(choice.equalsIgnoreCase("COLOR")){
return new ColorFactory();
}
return null;
}
}