简体   繁体   中英

Better to use constructor or method factory pattern?

I have a wrapper class for the Bitmap class called BitmapZone.

Assuming we have a WIDTH x HEIGHT bitmap picture, this wrapper class should serve the purpose of allowing me to send to other methods/classes itself instead of the original bitmap. I can then better control what the user is or not allowed to do with the picture (and I don't have to copy the bitmap lots of times to send for each method/class).

My question is: knowing that all BitmapZone's are created from a Bitmap, what do you find preferrable?

Constructor syntax: something like

BitmapZone bitmapZone = new BitmapZone(originalBitmap, x, y, width, height);

Factory Method Pattern:

BitmapZone bitmapZone = BitmapZone.From(originalBitmap, x , y, width, height);

Factory Method Pattern:

BitmapZone bitmapZone = BitmapZone.FromBitmap(originalBitmap, x, y, width, height);

Other? Why?

Thanks

In this instance, I see no reason to use a static method. The constructor works well and is the "obvious" way to construct a new BitmapZone.

You would normally fall back on a static method if you want to alter the construction behaviour. For instance, a caching mechanism that returns a previously constructed instance if the parameters are the same. This cannot be implemented via the constructor, which will always return a new instance.

I'd use the second factory method - it makes your code more readable and more intuitive for usage. If you haven't read Effective Java by Joshua Bloch, you'd better do this - it's a great book, and although it's not about C#, it will perfectly answer your question.

I'd prefer the latter example ( BitmapZone.FromBitmap ) over the middle one, only because it's more clear in its intent, with a negligible drop in brevity. Honestly, I don't have any preference between the first and the last examples; use the pattern that fits your architecture best. Review the advantages and disadvantages of the factory method pattern - whether it's right for you in this case depends of specifics of your design.

Myself, I'd start with a simple and straightforward constructor unless I had a good reason to do otherwise.

Put the method in Bitmap instead of BitmapZone .

BitmapZone bitmapZone = originalBitmap.GetZone(x, y)

You said it yourself: "Each BitmapZone is created from a Bitmap". This way you go from five parameters to two, since you don't need to pass in the bitmap, and each bitmap presumably knows its own width and height.
(How were you going to do that otherwise? new BitmapZone(originalBitmap, x, y, originalBitmap.Width, originalBitmap.Height) ? Ugly.)

If you can't change the Bitmap class, make it an extension method (though of course, that wouldn't work in Java).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM