I am making a drawing app for iOS and I have the following classes:
CanvasViewControllerholds aCanvasViewand allows you to select aBrushfor use in drawingCanvasViewis aUIViewthat contains a background color and an array ofStrokethat are rendered by wiring uptouchesevents anddrawRectStrokeis anNSObjectthat contains aUIBezierPath *pathand aBrushBrushcontains anint brushTypethat is defined by atypedefand can be things likeBrushTypeSolid, BrushTypeSpray, BrushTypePattern
Initially I thought about how I would handle drawing different brushType in my drawRect and it would be something like the following:
in drawrect
CGContextRef context = UIGraphicsGetCurrentContext();
UIGraphicsBeginImageContext(self.frame.size);
if ([squigglesArray count] > 0) {
for (WDSquiggle *squiggle in squigglesArray) {
[self drawSquiggle:squiggle inContext:context];
}
}
[self drawSquiggle:currentSquiggle inContext:context];
UIGraphicsEndImageContext();
in drawSquiggle
switch (squiggle.brushType): {
case BrushTypeSolid:
//solid brush stuff
break;
case BrushTypeX:
//x stuff
break;
}
However, now the drawing logic is all handled in a way that strongly ties the CanvasView and the BrushType together.
Is there an elegant way to encapsulate drawing logic in the BrushType or the Squiggle so that I could do something like:
[squiggle drawInRect:myRect]
or
[squiggle drawInView:myView]
Or, is this a stupid goal to have / I do not understand encapsulation?
You could turn
BrushTypeinto a class with subclasses for each specific implementation and move the related logic insidedrawSquiggleto it.drawSquigglewill simply call:(you can certainly find the best name and parameters for this method)
This is a refactoring called “replace conditional with polymorphism”.