工厂模式的原理
1.創建一個接口
public interface Shape{
? void draw();
}
2.創建實現接口的實體類
public class Rectangle implements Shape{
? ?public void draw(){
? ? ?sysout("inside Rectangle");
}
}
public class Square implements Shape{
? ?public void draw(){
? ? ?sysout("inside Square");
}
}
public class Circle implements Shape{
? ?public void draw(){
? ? ?sysout("inside Circle");
}
}
3.public class ShapFactory{
? ?//使用getShape方法獲取形狀類型的對象
? public Shape getShape(String shapeType){
? ? ? ? ?if(shapType==null){
? ? ? ? ? ? return null;}
? ? ? ? ?if(shapType.equalsIgnoreCase("CIRCLE")){
? ? ? ? ? ? ?return new Circle();
? ? ? ? ? ? }
? ? ? ? ? else if(shapType.equalsIgnoreCase("RECTANGLE")){
? ? ? ? ? ? return new Rectangle();
? ? ? ? ? ?}else if(shapType.equalsIgnoreCase("SQUARE")){
? ? ? ? ? ? ? ? ? return new square();
? ? ? ? ? ? ? }
? ? ? ?return null;
}
4.通過類型信息來獲取實體類的對象
public class FactoryPatternDemo{
? ? ?public static void main(String[] args){
? ? ? ? ? ? ?ShapeFactory shapeFactory=new Shapefactory();
? ? ? ? ? ? ?//獲取circle對象,并調用draw方法
? ? ? ? ? ? Shape shape1=shapFactory.getShape("CIRCLE");
? ? ? ? ? ? shape1.draw();
? ? ? ? ?}
}
總結
- 上一篇: Andorid App内部跟随熊语言改变
- 下一篇: 过滤器模式