设计模式六大原则(1):单一职责原则
设计模式六大原则(2):里氏替换原则
设计模式六大原则(3):依赖倒置原则
设计模式六大原则(4):接口隔离原则
设计模式六大原则(5):迪米特法则
设计模式六大原则(6):开闭原则
SimpleFactoryPattern,UML抽象图百度找,代码实现如下
使用简单工厂模式设计一个可以创建不同几何形状(如圆形、矩形和三角形等)的绘图工具,每个几何图形都要有计算面积area()和计算周长gride()两个方法
抽象产品类
package SimpleFactoryPattern;
public interface Product {
public float area();
public float gride();
}
具体产品类
package SimpleFactoryPattern.ConcreteProduct;
import SimpleFactoryPattern.Product;
public class Circular implements Product{
private float r;
public Circular(float r) {
this.r = r;
}
@Override
public float area() {
return 3.14f * r * r;
}
@Override
public float gride() {
return 3.14f * 2 * r;
}
}
package SimpleFactoryPattern.ConcreteProduct;
import SimpleFactoryPattern.Product;
public class Rectangle implements Product {
private float width;
private float height;
public Rectangle(float width, float height) {
this.width = width;
this.height = height;
}
@Override
public float area() {
return width * height * 1.0f;
}
@Override
public float gride() {
return (width + height) * 2.0f;
}
}
package SimpleFactoryPattern.ConcreteProduct;
import SimpleFactoryPattern.Product;
public class Triangle implements Product {
private float a;
private float b;
private float c;
public Triangle(float a, float b, float c) {
this.a = a;
this.b = b;
this.c = c;
}
@Override
public float area() {
float p = (a+b+c)/2.0f;
return (float) Math.sqrt(p*(p-a)*(p-b)*(p-c));
}
@Override
public float gride() {
return a+b+c;
}
}
简单工厂类
package SimpleFactoryPattern;
import java.util.Scanner;
import SimpleFactoryPattern.ConcreteProduct.Circular;
import SimpleFactoryPattern.ConcreteProduct.Rectangle;
import SimpleFactoryPattern.ConcreteProduct.Triangle;
public class Creator {
Scanner scan = new Scanner(System.in);
Product product=null;
public Product create(String type) { //工厂里的制造方法一定是静态吗!?
if("圆".equals(type)){
return new Circular(scan.nextFloat());
}else if("矩形".equals(type)){
return new Rectangle(scan.nextFloat(),scan.nextFloat());
}else if("三角形".equals(type)){
return new Triangle(scan.nextFloat(),scan.nextFloat(),scan.nextFloat());
}else{
return product;
}
}
}
测试类
package SimpleFactoryPattern;
public class Test {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Product product = new Creator().create("");
if(product==null){
System.out.println("请填写工厂条件");
}else{
System.out.println(product.area());
}
}
}
别嫌弃我没写注释,这个代码很简单,注释省略,嘿嘿。