0

我是设计模式的新手。我正在尝试在我当前的应用程序中使用工厂方法设计模式。在应用程序中,我有两个组(即 group1 和 group2),每个组都有不同的方法。将应用程序角色用作类并从产品(即 group2)继承是一种好习惯吗?谁能告诉我以下示例代码是对还是错。

class Creator
{
    static void Main(string[] args)
    {
        if (args[0] == "GroupHead")
        {
            IGroup2 gh = new GroupHead();
        }
        else if (args[0] == "ProjectIncharge")
        {
            IGroup2 gh = new ProjectIncharge();
        }
    }
}


interface IGroup1
{
    List<Employee> GetEmployees();
}

interface IGroup2
{
    List<Projects> GetProjects();
}

public class Group : IGroup1
{
    public List<Employee> GetEmployees()
    {
        //Code here
    }
}

public class GroupHead : IGroup2
{
    public List<Projects> GetProjects()
    {
        //Code here
    }
}

public class ProjectIncharge : IGroup2
{
    public List<Projects> GetProjects()
    {
        //Code here
    }
}

public class ProjectManager : IGroup2
{
    public List<Projects> GetProjects()
    {
        //Code here
    }
}
4

1 回答 1

0

您可以使用以下模式来执行此操作,它根据搜索选项返回以初始化对象。

        interface IGroup2
        {
            string SearchOption { get; set; }
            List<Projects> GetProjects();
        }

        public class GroupHead : IGroup2
        {
            public string SearchOption { get; set; }

            public GroupHead()
            {
                SearchOption = "GroupHead";
            }

            public List<Projects> GetProjects()
            {   
                //Code here
                return null;
            }
        }

        public class ProjectIncharge : IGroup2
        {
            public string SearchOption { get; set; }

            public ProjectIncharge()
            {
                SearchOption = "ProjectIncharge";
            }

            public List<Projects> GetProjects()
            {
                //Code here
                return null;
            }
        }

        public class ProjectManager : IGroup2
        {
            public string SearchOption { get; set; }

            public ProjectManager()
            {
                SearchOption = "ProjectManager";
            }

            public List<Projects> GetProjects()
            {
                //Code here
                return null;
            }
        }

public class Test
{
        private static List<IGroup2> searchRuleList = new List<IGroup2>()
        {
          new GroupHead(),
          new ProjectIncharge(),
          new ProjectManager(),
        };

        public static void Main(string[] args)
        {
         IGroup2 searchOptionRule = searchRuleList.Find(delegate(IGroup2 searchRule) { return searchRule.SearchOption.Equals(args[0]); });

        } 
}
于 2013-09-12T07:36:12.720 回答