2013-01-23 68 views
0

比方說,我有一個類,這個類包含一個公共屬性,它是一個System.Drawing.Bitmap,但我希望我的類的使用者能夠設置此值不同類型圖像的數量,而不必真正思考他們通過什麼,我會在幕後進行必要的轉換。這就是我的意思是:使用不同的數據類型設置屬性值

var myBitmapImage = new BitmapImage(); 
var writeableBitmap = new WriteableBitmap(myBitmapImage); 
var mySystemDrawingBitmap = new Bitmap(@"A:\b.c"); 

var classOne = new TestClass(); 
var classTwo = new TestClass(); 
var classThree = new TestClass(); 

//This should work: 
classOne.MyImage = myBitmapImage; 

//This should also work: 
classTwo.MyImage = writeableBitmap; 

//This should work too 
classThree.MyImage = mySystemDrawingBitmap; 

在此刻,我喜歡這樣想的東西:

public class TestClass 
{ 
    private Bitmap _myImage; 

    public object MyImage 
    { 
     get 
     { 
      return _myImage; 
     } 

     set 
     { 
      if (value is Bitmap) 
      { 
       _myImage = (Bitmap)value; 
      } 

      if (value is BitmapImage) 
      { 
       var imageAsSystemDrawingBitmap = ConvertBitmapImageToBitmap((BitmapImage)value); 
       _myImage = imageAsSystemDrawingBitmap; 
      } 

      if (value is WriteableBitmap) 
      { 
       var imageAsSystemDrawingBitmap = ConvertWriteableBitmapToBitmap((WriteableBitmap)value); 
       _myImage = imageAsSystemDrawingBitmap; 
      } 

      throw new Exception("Invalid image type"); 
     } 
    } 

    private Bitmap ConvertWriteableBitmapToBitmap(WriteableBitmap value) 
    { 
     //do work here 
     return null; 
    } 

    private Bitmap ConvertBitmapImageToBitmap(BitmapImage value) 
    { 
     //do work here 
     return null; 
    } 
} 

但使用對象和鑄造感覺很2001年,我相信必須有一個更雄辯的方式來實現這一點。有沒有,或者這首先是一個壞主意?

回答

2

您可以創建一個BitmapFactory類表現爲一個工廠來創建一個Bitmap,你可以閱讀更多關於Factory Design Pattern

public class TestClass 
{ 
    public BitmapFactory BitmapFactory { get; set; } 
    public Bitmap Bitmap { get { return this.BitmapFactory.Bitmap; } } 
} 

public interface IBitmapFactory 
{ 
    Bitmap Bitmap { get; } 
} 

public class BitmapFactory : IBitmapFactory 
{ 
    public Bitmap Bitmap { get; private set; } 

    public BitmapFactory(Bitmap value) 
    { 
     this.Bitmap = value; 
    } 

    public BitmapFactory(BitmapImage value) 
    { 
     this.Bitmap = ConvertBitmapImageToBitmap(value); 
    } 

    public BitmapFactory(WriteableBitmap value) 
    { 
     this.Bitmap = ConvertWriteableBitmapToBitmap(value); 
    } 

    private Bitmap ConvertWriteableBitmapToBitmap(WriteableBitmap value) 
    { 
     //do work here 
     return null; 
    } 

    private Bitmap ConvertBitmapImageToBitmap(BitmapImage value) 
    { 
     //do work here 
     return null; 
    } 
} 
+0

我知道,那裏是一個名字,但不記得是什麼它是或如何工作,非常感謝 – JMK

相關問題