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

Decorator Pattern (OOP)

M2000 is an interpreter, so make objects at runtime always. Here the decorator pattern used to add functionality (and type)  in a Circle type object (a group in M2000). So we don't extend the class Circle, but an object. We can merge two or more objects to be one object and the we make a new one from that. See this: Cir3=Circle(100) with ColorCircle(10)  we make a Circle of radius 100 and add a ColorCircle of pen color 10. The final object create the Cir3. Cir3 is a named group not a pointer to group. We can use Cir3 -> (Circle(100) with ColorCircle(10)) to make it a pointer to combined objects. Parenthesis needed because -> read one identifier or something in parenthesis. The same hold for pointer() which do the same (is identical with ->, but used where we can't use thin arrow ->)

We can make a Group without Type and we can add functionality without adding a type to final object. We can check if a named group has a specific method (module or function), using module() function. In the short example we didn't add a type, because Group aDecoration is typeless We can add types in a group putting a line Type: MyType1, MyType2

\\ Decoration Pattern (short example)
Class Anything {
Private:
      myvalue=100
Public:
      module DoSomething {
            Print "something"
      }
}
Group aDecoration {
      module DoSomething {
            Print "something change"
      }
      module DoSomethingElse (p as Anything){
            \\ we can read private myvalue from p
            \\ when this group is merged with a type Anything class
            Print "Do something Else", .myvalue+p.myvalue
      }
}
One=Anything() with aDecoration
One.DoSomethingElse Anything()
Two=Anything()
Two.DoSomething
Print module(Two.DoSomethingElse)=False
\\ adding later
Two=aDecoration
Two.DoSomething
Print module(Two.DoSomethingElse)=True



This is the Circle Example


\\ Decorator Pattern

Class Circle {
Private:
      radius
Public:
      module render (X, Y) {
            Print Format$("Draw a circle at {0},{1} of radius {2} using standard pen", X, Y, .radius)
      }
Class:
      module Circle (.radius) {
      }
}
Class ColorCircle {
Private:
      circlepen=0
Public:
      module render (X, Y) {
            Print Format$("Draw a circle at {0},{1} of radius {2} using pen {3}", X, Y, .radius,.circlepen)
      }
Class:
      module ColorCircle (.circlepen) {
      }      
}
Cir1=Circle(500)
Cir1.render 500, 400
\\ inheritance at object level composing two or more objects at right expression
Cir2=Cir1 with ColorCircle(15)
Cir2.render 120, 300
\\ inheritance at object level by merging to object.
Cir1=ColorCircle(13)
Cir1.render 500, 400
Cir3=Circle(100) with ColorCircle(10)
Cir3.render 200, 200

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

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

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