Reputation: 139
I have just started to learn about design patterns in C#.
I have two ComboBox and I need to change the content of the second ComboBox when the first ComboBox selected item is changed. Instead of using Switch statement, I'm not able to apply a design pattern here (factory design pattern I assume - from what I read so far).
class SomeClass
{
private const string CONST_LANG_1 = "LANGUAGE_1";
private const string CONST_LANG_2 = "LANGUAGE_2";
private const string CONST_LANG_3 = "LANGUAGE_3";
private const string CONST_LANG_4 = "LANGUAGE_4";
// ...
private const string CONST_LANG_1_SPK_1 = "SPEAKER_1_1";
private const string CONST_LANG_1_SPK_2 = "SPEAKER_1_2";
private const string CONST_LANG_2_SPK_1 = "SPEAKER_2_1";
private const string CONST_LANG_2_SPK_2 = "SPEAKER_2_2";
private const string CONST_LANG_3_SPK_1 = "SPEAKER_3_1";
private const string CONST_LANG_3_SPK_2 = "SPEAKER_3_2";
private const string CONST_LANG_4_SPK_1 = "SPEAKER_4_1";
private const string CONST_LANG_4_SPK_2 = "SPEAKER_4_2";
// ...
private void cmbSelectLanguageDEMO_SelectedIndexChanged(object sender, EventArgs e)
{
switch( cmbSelectLanguageDEMO.SelectedIndex )
{
case 0: // CONST_LANG_1 -> Populate cmbSelectSpeakerDEMO
break;
case 1: // CONST_LANG_2 -> Populate cmbSelectSpeakerDEMO
break;
// ...
}
}
}
Can someone help me to apply a design pattern here? I really want to learn how to implement a design pattern on my project.
Any help will be appreciated!
Upvotes: 0
Views: 201
Reputation: 2348
Not sure if the response is late.Maybe it is useful to somebody looking for similar solution. I feel the observer pattern might be what you are looking for.If you have an object whose state change should be notified to other objects then you use observer pattern.Here is a brief overview Observer design pattern.
Upvotes: 0
Reputation: 3784
I don't have a name for my suggestion design. But here is the best design I can think at the moment for you :)
interface Lang {
void List<String> speakers();
}
class Lang1 : Lang {
public override void List<String> speakers() {
return ...;
}
}
class Lang2 : Lang {
public override void List<String> speakers() {
return ...;
}
}
List<Lang> langs = new List<>();
int idx = 0;
langs[idx++] = new Lang1();
langs[idx++] = new Lang2();
private void cmbSelectLanguageDEMO_SelectedIndexChanged(object sender, EventArgs e) {
cmbSelectSpeakerDEMO.Items.AddRange( langs[cmbSelectLanguageDEMO.SelectedIndex].speakers() );
}
Upvotes: 2
Reputation: 4833
Have a look at strategy pattern https://en.wikipedia.org/wiki/Strategy_pattern
private void cmbSelectLanguageDEMO_SelectedIndexChanged(object sender, EventArgs e)
{
Action[] selectLanguageStrategies = {LoadLang1, LoadLang2 };
selectLanguageStrategies[cmbSelectLanguageDEMO.SelectedIndex]();
}
private void LoadLang1()
{
// CONST_LANG_1 -> Populate cmbSelectSpeakerDEMO
}
private void LoadLang2()
{
// CONST_LANG_2 -> Populate cmbSelectSpeakerDEMO
}
Upvotes: 1