VBオブジェクト指向プログラミング講座 第10回 小さなオブジェクトを合成して作ろう
オブジェクト指向プログラミングの初心者は、巨大なクラスを作る傾向があると思います。小さなオブジェクトはあまり便利に見えませんし、初心者の人は作っているという実感が得られないと思います。しかし、小さなオブジェクトを組み立てる考え方こそ、オブジェクト指向プログラミングの王道です。そうはいっても、目で確認しないと納得できないでしょう。そこで、目で分かるサンプルを用意しました。
前回までのサンプルを流用します。
Imports System
Imports System.Windows
Imports System.Windows.Controls
Imports System.Windows.Input
Imports System.Windows.Media '追加
Imports System.Windows.Shapes '追加
Friend Class MessageWindow
'他のプログラムは省略
Public Sub New(Optional ByVal msg As String = "Hello World")
'他のプログラムは省略
'..........
'ボタン
Dim btn = CreateEllipseButton() 'ここを変更
End Sub
'楕円ボタンを作成する関数を追加
Private Function CreateEllipseButton() As Button
'原型となるボタン
Dim btn As Button = New Button()
'ファクトリーオブジェクトを用意
Dim mainFact As FrameworkElementFactory =
New FrameworkElementFactory(GetType(Grid))
'楕円を用意
Dim brush As LinearGradientBrush = New LinearGradientBrush()
brush.EndPoint = New Point(0, 1)
brush.GradientStops.Add(
New GradientStop(Color.FromArgb(100, 255, 255, 0), 0))
brush.GradientStops.Add(
New GradientStop(Color.FromArgb(255, 0, 255, 0), 1))
Dim ellipseFact As FrameworkElementFactory =
New FrameworkElementFactory(GetType(Ellipse))
ellipseFact.SetValue(
Ellipse.StrokeThicknessProperty, 5.0)
ellipseFact.SetValue(
Ellipse.FillProperty, brush)
mainFact.AppendChild(ellipseFact)
'楕円の位置
Dim position As FrameworkElementFactory =
New FrameworkElementFactory(GetType(ContentPresenter))
position.SetValue(
ContentPresenter.HorizontalAlignmentProperty,
HorizontalAlignment.Center)
position.SetValue(
ContentPresenter.VerticalAlignmentProperty,
VerticalAlignment.Center)
mainFact.AppendChild(position)
'ボタンにテンプレートを適用
Dim tmp As ControlTemplate =
New ControlTemplate(GetType(Button))
tmp.VisualTree = mainFact
btn.Template = tmp
Return btn
End Function
End Class
サンプルを実行すると、メインとなるボタンの形が、楕円に変化している事が一目で分かります。WPFを知らないとプログラムの詳細が分からないと思いますが、今は気にしないでください。今回の記事は、オブジェクト指向プログラミングの考え方がテーマです。プログラムの細かい意味は分からないかもしれませんが、小さなオブジェクトでボタンが作られている事は分かって頂けると思います。マイクロソフト社にいる凄く優秀な人が設計しただけあって、理想的なオブジェクトで構成されています。WPFは小さなオブジェクトを組み合わせて、柔軟かつ強力なプログラミングが出来ます。これこそが、オブジェクト指向プログラミングの魂だと言えます。
オブジェクト指向プログラミングの基本は、「小さなオブジェクトを作って大きく組み立てる」です。もちろん、意味がないオブジェクトを定義しても駄目ですが、大きなオブジェクトを作ると、逆に使い勝手が悪くなります。オブジェクトは小さく作る事を心掛けましょう。続く...