code_junkie

Design pattern suitable for the task

Nov 13th, 2011
152
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.18 KB | None | 0 0
  1. ImageBase {}
  2. JpegImage : ImageBase {}
  3. TiffImage : ImageBase{}
  4.  
  5. var image=ImageBase.GetImageFromDisk(path);
  6. //some casting to subclass maybe??
  7. var tiffImage=image as TiffImage;
  8. tiffImage.Location=new FtpLocation();//not sure if this is a good idea
  9. tiffImage.Save();
  10.  
  11. public void Save()
  12. {
  13. // TODO: add any language-specific constructs like "using", etc
  14. Stream stream = Location.OpenWrite();
  15. Save(stream);
  16. stream.Close();
  17. }
  18.  
  19. protected abstract void Save(Stream stream);
  20.  
  21. public static ImageBase Load(Location location)
  22. {
  23. // TODO: add any language-specific constructs like "using", etc
  24. Stream stream = location.OpenRead();
  25. // TODO: wrap in a buffered/seekable stream so we can peek
  26. // TODO: parse headers and resolve image type
  27. ImageBase image = ...
  28. image.Location = location;
  29. stream.Position = 0; // rewind buffered/seekable stream
  30. // (don't use Load() since we have already opened the stream)
  31. image.Load(stream);
  32. stream.Close();
  33. return image;
  34. }
  35. protected abstract void Load(Stream stream);
  36. public void Load()
  37. {
  38. // TODO: add any language-specific constructs like "using", etc
  39. Stream stream = Location.OpenRead();
  40. Load(stream); // don't need to buffer if loading from subclass
  41. stream.Close();
  42. }
  43.  
  44. public class Image {
  45. public void load(byte[] imageData);
  46. public byte[] getImageData();
  47. }
  48.  
  49. public class JpegImage extends Image {
  50. public void load(byte[] imageData) {
  51. /* decode image data. */
  52. }
  53.  
  54. public byte[] getImageData() {
  55. /* encode and return the JPG data. */
  56. }
  57. }
  58.  
  59. public class Location {
  60. public Image loadImage(String uri);
  61. public void saveImage(Image image);
  62. }
  63.  
  64. public class HttpLocation extends Location {
  65. public Image loadImage(String uri) {
  66. byte[] = getData(uri);
  67. if (type == JPEG) {
  68. return new JpegImage().load(byte);
  69. } else if (type == PNG) {
  70. return new PngImage().load(byte);
  71. }
  72. }
  73. public void saveImage(Image image) {
  74. byte[] imageData = image.getImageData();
  75. /* upload. */
  76. }
  77. }
  78.  
  79. Image
  80.  
  81. ImageFormat { Save(Image, Stream); Image Load(Stream); }
  82. JpegFormat : ImageFormat {}
  83. TiffFormat : ImageFormat {}
Add Comment
Please, Sign In to add comment