工厂模式笔记
参考教程
主要参考了 抽象工厂模式 和 工厂模式-简单工厂、工厂方法、抽象工厂解析
代码部分
要生产的产品
package fun.seolas.factory.simple;
public class Product {
}
/**
* 形状产品
*/
interface Shape {
void draw();
}
class Circle implements Shape {
@Override
public void draw() {
System.out.println("circle");
}
}
class Square implements Shape {
@Override
public void draw() {
System.out.println("square");
}
}
/**
* 颜色产品
*/
interface Color {
void fill();
}
class Red implements Color {
@Override
public void fill() {
System.out.println("red");
}
}
class Bule implements Color {
@Override
public void fill() {
System.out.println("blue");
}
}
简单工厂模式
package fun.seolas.factory.simple;
/**
* 简单工厂模式:
* 只提供传入工厂的参数,由工厂来创建对象
*/
public class SimpleFactoryDemo {
public static void main(String[] args) {
ShapeFactory shapeFactory = new ShapeFactory();
Shape circle = shapeFactory.getShape("circle");
circle.draw();
}
}
class ShapeFactory {
Shape getShape(String shape) {
if ("circle".equals(shape)) {
return new Circle();
} else if ("square".equals(shape)) {
return new Square();
}
return null;
}
}
工厂方法模式
package fun.seolas.factory.method;
/**
* 工厂方法模式:
* 不传参数了,一个工厂生产指定的产品
*/
public class FactoryMethodDemo {
public static void main(String[] args) {
CircleFactory circleFactory = new CircleFactory();
Shape circle = circleFactory.getShape();
circle.draw();
}
}
abstract class ShapeFactory {
abstract Shape getShape();
}
class CircleFactory extends ShapeFactory {
@Override
Shape getShape() {
return new Circle();
}
}
class SquareFactory extends ShapeFactory {
@Override
Shape getShape() {
return new Square();
}
}
抽象工厂模式
package fun.seolas.factory.abs;
/**
* 抽象工厂模式:
* 传入参数,指定要哪个工厂,再传入参数,生成指定产品
*/
public class AbstractFactoryDemo {
public static void main(String[] args) {
AbstractFactory shapeFactory = FactoryProducer.getFactory("shape");
Shape circle = shapeFactory.getShape("circle");
circle.draw();
}
}
class FactoryProducer {
static AbstractFactory getFactory(String choice) {
if ("shape".equals(choice)) {
return new ShapeFactory();
} else if ("color".equals(choice)) {
return new ColorFactory();
}
return null;
}
}
abstract class AbstractFactory {
abstract Shape getShape(String shape);
abstract Color getColor(String color);
}
class ShapeFactory extends AbstractFactory {
@Override
Shape getShape(String shape) {
if ("circle".equals(shape)) {
return new Circle();
} else if ("square".equals(shape)) {
return new Square();
}
return null;
}
@Override
Color getColor(String color) {
return null;
}
}
class ColorFactory extends AbstractFactory {
@Override
Shape getShape(String shape) {
return null;
}
@Override
Color getColor(String color) {
if ("red".equals(color)) {
return new Red();
} else if ("blue".equals(color)) {
return new Bule();
}
return null;
}
}