C# 入门版:
namespace FactoryPattern { /// <summary> /// 方式1:接口作为父类 /// </summary> public interface ISayHello { void SayHello(); } /// <summary> /// 汉语 /// </summary> public class Chinese : ISayHello { private string _name; public Chinese() { } public Chinese(string name) { _name = name; } public void SayHello() { Console.WriteLine("大家好,我是 " + _name); } } /// <summary> /// 英语 /// </summary> public class American : ISayHello { private string _name; public American() { } public American(string name) { _name = name; } public void SayHello() { Console.WriteLine("Hello Everyone, I'm " + this._name); } } /// <summary> /// 日语 /// </summary> public class Japanese : ISayHello { public void SayHello() { Console.WriteLine("こんにちは、我是小日子过的不错的日本人"); } } public enum LanguageType { Chinese, English, Janpanese } /// <summary> /// 工厂类 /// </summary> public class LanguageFactory { public static ISayHello GetLanguage(LanguageType type) { switch (type) { case LanguageType.Chinese: return new Chinese("小明"); case LanguageType.English: return new American("MJ"); case LanguageType.Janpanese: return new Japanese(); default: return null; } } } /// <summary> /// /// </summary> internal class Program { static void Main(string[] args) { LanguageFactory.GetLanguage(LanguageType.Chinese).SayHello(); LanguageFactory.GetLanguage(LanguageType.English).SayHello(); LanguageFactory.GetLanguage(LanguageType.Janpanese).SayHello(); Console.ReadKey(); } } }
版权声明:
本文来源网络,所有图片文章版权属于原作者,如有侵权,联系删除。
本文网址:https://www.bianchenghao6.com/java-jiao-cheng/10858.html