设计模式—创建型

设计模式—创建型,第1张

1.工厂模式
  • 概述
1.不会向客户端暴露创建对象逻辑,提供公共接口指向创建的对象
2.调用者创建对象,只需要知道该对象的名称
3.每次增加产品都要增加具体产品类和工厂类中else-if
4.复杂对象的创建适合使用工厂模式,对于简单对象,使用工厂模式会增加系统复杂度
  • 类图
  • 讲解
1.实现Shape接口实现Shape接口的实体类
2.定义工厂类ShapeFactory,根据传入的类型名创建Shape的具体实现类
3.FactoryPatternDemo类使用ShapeFactory来获取Shape对象,它将向ShapeFactory传递信息
  • 实现
//1.创建产品接口
public interface Shape{
	void draw();
}
//2.创建具体产品类
public class Circle implements Shape {
	@Override
    public void draw() {
    	System.out.println("Circle-draw");
   }
}
public class Square implements Shape {
	@Override
    public void draw() {
    	System.out.println("Square-draw");
    }
}
public class Rectangle implements Shape{
	@Override
    public void draw() {
	    System.out.println("Rectangle-draw");
    }
}
//3.创建工厂用于实例化对象—只需要知道产品名
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;
   }
}
----------------------------------------
main(){
	//1.创建工厂
	ShapeFactory shapeFactory = new ShapeFactory();
	//2.告诉工厂产品名,让工厂new相应产品
    Shape shape1 = shapeFactory.getShape("CIRCLE");//创建Circle的对象
    shape1.draw();//调用Circle的draw
}
2.抽象工厂模式
  • 概述
1.围绕超级工厂创建其他工厂,接口主要负责创建相应对象的工厂
  • 类图
  • 讲解
1.Shape和Color接口和实现这些接口的实体类
2.创建抽象工厂类AbstractFactory,管理具体产品接口
3.定义具体产品工厂类ShapeFactoryColorFactory,这两个工厂类都扩展AbstractFactory,管理每个产品接口下的具体产品
4.创建超级工厂FactoryProducer,创建具体产品工厂
5.AbstractFactoryPatternDemo类使用FactoryProducer来获取AbstractFactory对象,它将向AbstractFactory传递形状信息Shape以便获取它所需对象的类型;同时它还向 AbstractFactory传递颜色信息Color以便获取它所需对象的类型
  • 实现
//1.创建形状产品接口
public interface Shape{
	void draw();
}
//2.创建具体产品类
public class Circle implements Shape {
	@Override
    public void draw() {
    	System.out.println("Circle-draw");
   }
}
public class Square implements Shape {
	@Override
    public void draw() {
    	System.out.println("Square-draw");
    }
}
public class Rectangle implements Shape{
	@Override
    public void draw() {
	    System.out.println("Rectangle-draw");
    }
}
//3.创建颜色产品接口
public interface Color {
   void fill();
}
//4.创建具体产品类
public class Red implements Color {
   @Override
   public void fill() {
      System.out.println("Red-fill");
   }
}
public class Green implements Color {
   @Override
   public void fill() {
      System.out.println("Green-fill");
   }
}
public class Blue implements Color {
   @Override
   public void fill() {
      System.out.println("Blue-fill");
   }
}
//5.创建工厂抽象类
public abstract class AbstractFactory {
   public abstract Color getColor(String color);
   public abstract Shape getShape(String shape);
}
//6.创建工厂实例化对象
public class ShapeFactory extends AbstractFactory { 
   @Override
   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
   public Color getColor(String color) {
      return null;
   }
}
public class ColorFactory extends AbstractFactory {
   @Override
   public Shape getShape(String shapeType){
      return null;
   }
   
   @Override
   public Color getColor(String color) {
      if(color == null){
         return null;
      }        
      if(color.equalsIgnoreCase("RED")){
         return new Red();
      } else if(color.equalsIgnoreCase("GREEN")){
         return new Green();
      } else if(color.equalsIgnoreCase("BLUE")){
         return new Blue();
      }
      return null;
   }
}
//7.创建超级工厂
public class FactoryProducer {
   public static AbstractFactory getFactory(String choice){
      if(choice.equalsIgnoreCase("SHAPE")){
         return new ShapeFactory();
      } else if(choice.equalsIgnoreCase("COLOR")){
         return new ColorFactory();
      }
      return null;
   }
}
----------------------------------------
main(){
	//1.创建形状工厂
	AbstractFactory shapeFactory = FactoryProducer.getFactory("SHAPE");
	//2.告诉产品名,new相应产品
    Shape shape1 = shapeFactory.getShape("CIRCLE");//创建Circle的对象
    shape1.draw();//调用Circle的draw
}
3.单例模式
  • 概述
1.确保单例类只能创建自己的唯一实例,并向外提供该实例
2.唯一实例节省系统创建销毁实例时间,减少内存开销
  • 饿汉式(类加载时实例化)
class Singleton{
	private static Singleton instance = new Singleton();//线程安全
	private Singleton(){}
	public static Singleton getInstance(){
		return instance;
	}
}
  • 懒汉式(使用时实例化)
class Singleton{
	private static Singleton instance;
	private Singleton(){}
	public synchronized static Singleton getInstance(){//加锁:防止多线程情况下被多次new——加锁线程安全
		if(instance==null){
			instance = new Singleton();
		}
		return instance;
	}
}
  • 双重检查锁单例模式
class Singleton{
	private volatile static Singleton instance;//volatile关键字避免重排序
	private Singleton(){}
	public static Singleton getInstance(){//减小锁的范围
		if(instance==null){
			synchronized(Singleton.class){
				if(instance==null){
					instance = new Singleton();
				}
			}
		}
		return instance;
	}
}
4.建造者模式
  • 概述
1.用于构建复杂对象,子对象常由算法构成,由于需求变化,复杂对象的各个子对象面临剧烈变化,但将子对象组合的算法相对稳定
2.将变与不变分离
  • 类图
  • 讲解
1.假设快餐店的商业案例,其中典型套餐是一个汉堡(Burger)和一杯冷饮(Cold drink)
2.汉堡(Burger)可以是素食汉堡(Veg Burger)或鸡肉汉堡(Chicken Burger),它们是包在纸盒中
3.冷饮(Cold drink)可以是可口可乐(coke)或百事可乐(pepsi),它们是装在瓶子中
4.创建表示食物条目的Item接口和实现Item接口的实体类,以及表示食物包装的Packing接口和实现Packing接口的实体类,汉堡是包在纸盒中,冷饮是装在瓶子中
5.创建Meal类,其中包含带有ItemArrayList
6.通过结合Item来创建不同类型的Meal对象的 MealBuilder
7.BuilderPatternDemo类使用MealBuilder来创建Meal
  • 实现
//1.创建表示食物条目和食物包装的接口
public interface Item {
   public String name();
   public Packing packing();
   public float price();    
}
public interface Packing {
   public String pack();
}
//2.创建实现Packing接口的实体类(具体包装工具)
public class Wrapper implements Packing {
   @Override
   public String pack() {
      return "Wrapper";
   }
}
public class Bottle implements Packing {
   @Override
   public String pack() {
      return "Bottle";
   }
}
//3.创建实现Item接口的抽象类,该类提供了默认的功能
public abstract class Burger implements Item {//汉堡
   @Override
   public Packing packing() {
      return new Wrapper();
   } 
   @Override
   public abstract float price();
}
public abstract class ColdDrink implements Item {//冷饮
    @Override
    public Packing packing() {
       return new Bottle();
    }
    @Override
    public abstract float price();
}
//4.创建Burger和ColdDrink的实体类(具体食品种类)
public class VegBurger extends Burger { 
   @Override
   public float price() {
      return 25.0f;
   }
   @Override
   public String name() {
      return "Veg Burger";
   }
}
public class ChickenBurger extends Burger { 
   @Override
   public float price() {
      return 50.5f;
   } 
   @Override
   public String name() {
      return "Chicken Burger";
   }
}
public class Coke extends ColdDrink { 
   @Override
   public float price() {
      return 30.0f;
   }
   @Override
   public String name() {
      return "Coke";
   }
}
public class Pepsi extends ColdDrink {
   @Override
   public float price() {
      return 35.0f;
   }
   @Override
   public String name() {
      return "Pepsi";
   }
}
//5.管理Item套餐组合基本 *** 作
public class Meal {
   private List<Item> items = new ArrayList<Item>();    
 
   public void addItem(Item item){
      items.add(item);
   }
 
   public float getCost(){
      float cost = 0.0f;
      for (Item item : items) {
         cost += item.price();
      }        
      return cost;
   }
 
   public void showItems(){
      for (Item item : items) {
         System.out.print("Item : "+item.name());
         System.out.print(", Packing : "+item.packing().pack());
         System.out.println(", Price : "+item.price());
      }        
   }    
}
//6.不同套餐
public class MealBuilder {
   public Meal prepareVegMeal (){
      Meal meal = new Meal();
      meal.addItem(new VegBurger());
      meal.addItem(new Coke());
      return meal;
   }   
   public Meal prepareNonVegMeal (){
      Meal meal = new Meal();
      meal.addItem(new ChickenBurger());
      meal.addItem(new Pepsi());
      return meal;
   }
}
----------------------------------------
main(){
	MealBuilder mealBuilder = new MealBuilder();
	//买VegMeal套餐
	Meal vegMeal = mealBuilder.prepareVegMeal();
	vegMeal.showItems();
	System.out.println("Total Cost: " +vegMeal.getCost());
}
5.原型模式
  • 概述
1.创建重复对象的同时保证性能
2.原型对象用于创建该对象的克隆,因为直接创建对象的代价太大,克隆对象在运行期间创建和删除
  • 类图
  • 讲解
1.创建抽象类Shape和扩展Shape类的实体类
2.定义类ShapeCache,该类通过loadCache方法将所有Shape实现类对象存储在Hashtable中,并在请求的时候返回它们的克隆
3.PrototypePatternDemo类使用ShapeCache类来获取Shape对象
  • 实现
//1.创建实现Cloneable接口的抽象类
public abstract class Shape implements Cloneable {
   private String id;
   protected String type;
   
   abstract void draw();
   
   public String getType(){return type;}
   public String getId(){return id;}
   public void setId(String id){this.id = id;}
   
   public Object clone(){
      Object clone = null;
      try {
         clone = super.clone();
      } catch (CloneNotSupportedException e) {
         e.printStackTrace();
      }
      return clone;
   }
}
//2.创建具体产品类
public class Circle implements Shape {
	public Circle(){
        type = "Circle";
    }
	@Override
    public void draw() {
    	System.out.println("Circle-draw");
   }
}
public class Square implements Shape {
	public Square(){
        type = "Square";
    }
	@Override
    public void draw() {
    	System.out.println("Square-draw");
    }
}
public class Rectangle implements Shape {
	public Rectangle(){
        type = "Rectangle";
    }
	@Override
    public void draw() {
    	System.out.println("Rectangle-draw");
    }
}
//3.创建类从数据库获取实体类,并存储在 Hashtable中
public class ShapeCache {
   //保存查询结果
   private static Hashtable<String, Shape> shapeMap = new Hashtable<String, Shape>();
 
   //对每种形状都运行数据库查询,并创建该形状
   public static void loadCache() {
      Circle circle = new Circle();
      circle.setId("1");
      shapeMap.put(circle.getId(),circle);
 
      Square square = new Square();
      square.setId("2");
      shapeMap.put(square.getId(),square);
 
      Rectangle rectangle = new Rectangle();
      rectangle.setId("3");
      shapeMap.put(rectangle.getId(),rectangle);
   }
   
   public static Shape getShape(String shapeId) {
      Shape cachedShape = shapeMap.get(shapeId);
      return (Shape) cachedShape.clone();
   }  
}
----------------------------------------
main(){
	ShapeCache.loadCache();
	
	Shape clonedShape = (Shape) ShapeCache.getShape("1");
	System.out.println("Shape : " + clonedShape.getType());        
	
	Shape clonedShape2 = (Shape) ShapeCache.getShape("2");
	System.out.println("Shape : " + clonedShape2.getType());        
	
	Shape clonedShape3 = (Shape) ShapeCache.getShape("3");
	System.out.println("Shape : " + clonedShape3.getType());     

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/874401.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-13
下一篇 2022-05-13

发表评论

登录后才能评论

评论列表(0条)

保存