Τετάρτη 15 Ιουλίου 2020

Proxy Pattern (OOP)

The proxy pattern has a Proxy class which inherits from a Subject class and a reference of a RealSubject, which also inherits from Subject class. We can use the proxy as the RealSubject. Here we have a proxy for a picture from a file. We want first to put the name to object. We want to see that name and maybe we want to load and draw the picture to screen. The RealSubject has a function to load the picture and return true if the picture loaded. Also mark the state so when we decide to draw check the state and do the drawing. The proxy combine the load and draw in the draw operation. We can use the proxy as a RealSubject, because has the same interface, but the methodC has advance logic, and can be used as for RealSubject if first we use methodB() or as the proxy using methodC which handle the state and can decide to call methodB() on the RealSubject which hold a pointer to any class support Subject interface. (M2000 hasn't interfaces, but we mimic that using classes with erroneous methods, which raise error "Abstract" or anything else)



\\ Proxy Pattern


class Subject {
private:      
      filename$, loadpicture
Public:
      module methodA {
            error "Abstact"
      }
      function methodB {
            error "Abstact"
      }
      module methodC {
            error "Abstact"            
      }      
}
class Proxy as Subject {
      RealSubject=pointer()
      module methodA {
            .RealSubject=>methodA
      }
      function methodB {
            if not .loadpicture then .loadpicture<=.RealSubject=>methodB()
            =.loadpicture
      }
      module methodC {
            if not .loadpicture then
                  .loadpicture<=.RealSubject=>methodB()
            end if
            .RealSubject=>methodC
      }            
class:
      module Proxy (p as *Subject) {
            .RealSubject<=p
      }
}
class RealSubject as Subject {
      module methodA {
            Print "The name of a file of a picture:"; .filename$
      }
      function methodB {
            .loadpicture<=true
            Print "Load the picture"
            =.loadpicture
      }
      module methodC {
            if .loadpicture then
                  Print "Draw the picture"
            End if
      }
class:
      module RealSubject (.filename$) {
      }
}
M=RealSubject("alfa.bmp")
M.methodA
if M.methodB() then M.methodC
\\ Now we make the proxy
K=Proxy(Pointer(RealSubject("beta.bmp")))
K.methodA
\\ proxy may call an operation methodB before actually call the methodC
K.methodC
K.methodC


Δεν υπάρχουν σχόλια:

Δημοσίευση σχολίου

You can feel free to write any suggestion, or idea on the subject.