1. 程式人生 > >移動開發之設計模式-原型模式(IOS&Android)

移動開發之設計模式-原型模式(IOS&Android)

資源

完全參照 原型模式|菜鳥教程 ,但不包括IOS程式碼

原型模式

原型模式(Prototype Pattern)是用於建立重複的物件,同時又能保證效能。這種型別的設計模式屬於建立型模式,它提供了一種建立物件的最佳方式。
這種模式是實現了一個原型介面,該介面用於建立當前物件的克隆。當直接建立物件的代價比較大時,則採用這種模式。例如,一個物件需要在一個高代價的資料庫操作之後被建立。我們可以快取該物件,在下一個請求時返回它的克隆,在需要的時候更新資料庫,以此來減少資料庫呼叫。

介紹

意圖: 用原型例項指定建立物件的種類,並且通過拷貝這些原型建立新的物件。
主要解決:

在執行期建立和刪除原型。
何時使用:
1、當一個系統應該獨立於它的產品建立,構成和表示時。
2、當要例項化的類是在執行時刻指定時,例如,通過動態裝載。
3、為了避免建立一個與產品類層次平行的工廠類層次時。
4、當一個類的例項只能有幾個不同狀態組合中的一種時。建立相應數目的原型並克隆它們可能比每次用合適的狀態手工例項化該類更方便一些。
如何解決: 利用已有的一個原型物件,快速地生成和原型物件一樣的例項。
關鍵程式碼:
1、實現克隆操作,在 JAVA 繼承 Cloneable,重寫 clone(),在 .NET 中可以使用 Object 類的 MemberwiseClone() 方法來實現物件的淺拷貝或通過序列化的方式來實現深拷貝。
2、原型模式同樣用於隔離類物件的使用者和具體型別(易變類)之間的耦合關係,它同樣要求這些"易變類"擁有穩定的介面。

應用例項:
1、細胞分裂。
2、JAVA 中的 Object clone() 方法。

優點:
1、效能提高。
2、逃避建構函式的約束。

缺點:
1、配備克隆方法需要對類的功能進行通盤考慮,這對於全新的類不是很難,但對於已有的類不一定很容易,特別當一個類引用不支援序列化的間接物件,或者引用含有迴圈結構的時候。
2、必須實現 Cloneable 介面。

使用場景:
1、資源優化場景。
2、類初始化需要消化非常多的資源,這個資源包括資料、硬體資源等。
3、效能和安全要求的場景。
4、通過 new 產生一個物件需要非常繁瑣的資料準備或訪問許可權,則可以使用原型模式。
5、一個物件多個修改者的場景。
6、一個物件需要提供給其他物件訪問,而且各個呼叫者可能都需要修改其值時,可以考慮使用原型模式拷貝多個物件供呼叫者使用。
7、在實際專案中,原型模式很少單獨出現,一般是和工廠方法模式一起出現,通過 clone 的方法建立一個物件,然後由工廠方法提供給呼叫者。原型模式已經與 Java 融為渾然一體,大家可以隨手拿來使用。

注意事項: 與通過對一個類進行例項化來構造新物件不同的是,原型模式是通過拷貝一個現有物件生成新物件的。淺拷貝實現 Cloneable,重寫,深拷貝是通過實現 Serializable 讀取二進位制流。

在這裡插入圖片描述

#Android

Shape.java

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;
   }
}

Rectangle.java

public class Rectangle extends Shape {
 
   public Rectangle(){
     type = "Rectangle";
   }
 
   @Override
   public void draw() {
      System.out.println("Inside Rectangle::draw() method.");
   }
}

Square.java

public class Square extends Shape {
 
   public Square(){
     type = "Square";
   }
 
   @Override
   public void draw() {
      System.out.println("Inside Square::draw() method.");
   }
}

Circle.java

public class Circle extends Shape {
 
   public Circle(){
     type = "Circle";
   }
 
   @Override
   public void draw() {
      System.out.println("Inside Circle::draw() method.");
   }
}

ShapeCache.java

public class ShapeCache {
    
   private static Hashtable<String, Shape> shapeMap 
      = new Hashtable<String, Shape>();
 
   public static Shape getShape(String shapeId) {
      Shape cachedShape = shapeMap.get(shapeId);
      return (Shape) cachedShape.clone();
   }
 
   // 對每種形狀都執行資料庫查詢,並建立該形狀
   // shapeMap.put(shapeKey, 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);
   }
}

PrototypePatternDemo.java

public class PrototypePatternDemo {
   public static void main(String[] args) {
      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());        
   }
}

結果

Shape : Circle
Shape : Square
Shape : Rectangle

IOS

Shape.h

#import <Foundation/Foundation.h>

NS_ASSUME_NONNULL_BEGIN

@protocol Cloneable <NSObject>
-(id)clone;
@end

@interface Shape : NSObject <Cloneable>

@property (nonatomic, strong) NSString * id;
@property (nonatomic, strong) NSString * type;

-(void)draw;
@end

@interface Rectangle : Shape
@end

@interface Square : Shape
@end

@interface Circle : Shape
@end
NS_ASSUME_NONNULL_END

Shape.m

#import "Shape.h"

@implementation Shape

- (void)draw{}
- (id)clone{
    Shape* shape = Shape.new;
    shape.id = self.id;
    shape.type = self.type;
    return shape;
}
@end


@implementation Rectangle

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.type = @"Rectangle";
    }
    return self;
}

- (void)draw{
    NSLog(@"Inside Rectangle::draw() method.");
}

- (id)clone{
    Rectangle *rectangle = Rectangle.new;
    rectangle.id = self.id;
    rectangle.type = self.type;
    return rectangle;
}

@end


@implementation Square

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.type = @"Square";
    }
    return self;
}

- (void)draw{
    NSLog(@"Inside Squre::draw() method.");
}

- (id)clone{
    Square *square = Square.new;
    square.id = self.id;
    square.type = self.type;
    return square;
}

@end


@implementation Circle

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.type = @"Circle.";
    }
    return self;
}

- (void)draw{
    NSLog(@"Inside Circle::draw() method.");
}

- (id)clone{
    Circle * circle = Circle.new;
    circle.id = self.id;
    circle.type = self.type;
    return circle;
}

@end

ShapeCache.h

#import <Foundation/Foundation.h>
#import "Shape.h"

NS_ASSUME_NONNULL_BEGIN

@interface ShapeCache : NSObject
-(Shape*) getShape:(NSString*)shapeId;
-(void) loadCache;
@end

NS_ASSUME_NONNULL_END

##ShapeCache.m

#import "ShapeCache.h"
#import "Shape.h"

@interface ShapeCache ()
@property (nonatomic, strong) NSMutableDictionary * shapeMap;
@end
@implementation ShapeCache

- (NSMutableDictionary *)shapeMap{
    if(!_shapeMap) {
        _shapeMap = [[NSMutableDictionary alloc] init];
    }
    return _shapeMap;
}

-(Shape*) getShape:(NSString*)shapeId{
    Shape *cachedShape = [self.shapeMap objectForKey:shapeId];
    return [cachedShape clone];
}

//對每種形狀都執行資料庫查詢,並建立該形狀
//shapeMap.put(shapeKey, shape);
//例如,我們要新增三種形狀
-(void) loadCache{
    Circle *circle = Circle.new;
    circle.id = @"1";
    [self.shapeMap setObject:circle forKey:circle.id];
    
    Square *square = Square.new;
    square.id = @"2";
    [self.shapeMap setObject:square forKey:square.id];
    
    Rectangle *rectangle = Rectangle.new;
    rectangle.id = @"3";
    [self.shapeMap setObject:rectangle forKey:rectangle.id];
}

## ViewController

  • (void)viewDidLoad{
    ShapeCache* shapeCache = ShapeCache.new;
    [shapeCache loadCache];

    Shape *clonedShape = [shapeCache getShape:@“1”];
    NSLog(@“Shape : %@”, clonedShape.type);

    Shape *cloneShape2 = [shapeCache getShape:@“2”];
    NSLog(@“Shape : %@”, cloneShape2.type);

    Shape *cloneShape3 = [shapeCache getShape:@“3”];
    NSLog(@“Shape : %@”, cloneShape3.type);
    }


@end

結果

Shape : Circle.
Shape : Square
Shape : Rectangle