Chad, > I had the same issue recently, how do I implement a factory > pattern in C#, having the consumer classes of the factory, the > factory itself, and the classes it creates all residing in the > same assembly but not allowing the consumer classes to create any > of the classes that will be created through the factory. Well > there is no direct scope level that allows this. The solution > would be to create internals in a different assembly but that's > not what I wanted. So this is what I did: > > 1) define the common factory interface as public > 2) define the factory class as public with the factory > method that returns an interface defined in (1) > 3) define all classes that implement the interface in (1) > as private, nested classes inside the factory class > <snipped code>
That's a useful technique. Another approach you can use is to make the factory an base of the individual classes you need as in the following. <code> using System; namespace ConsoleApplication1 { public abstract class BaseClass { private BaseClass() { } public static BaseClass Create(string someInfo) { switch (someInfo) { case "abc": return new DerivedClass1(); case "xyz": return new DerivedClass2(); default: throw new ArgumentException( "I don't know how to create " + someInfo ); } } public virtual void DoSomething() { } // Nested derived classes private class DerivedClass1 : BaseClass { public override void DoSomething() { Console.WriteLine("DerivedClass1 did something"); } } private class DerivedClass2 : BaseClass { public override void DoSomething() { Console.WriteLine("DerivedClass2 did something"); } } } /// <summary> /// Summary description for Class1. /// </summary> class Class1 { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main(string[] args) { try { BaseClass obj1 = BaseClass.Create("abc"); obj1.DoSomething(); BaseClass obj2 = BaseClass.Create("xyz"); obj2.DoSomething(); BaseClass obj3 = BaseClass.Create("123"); obj3.DoSomething(); } catch (Exception e) { Console.WriteLine ( e.Message ); } // This gives compiler error // Cannot create an instance of the abstract class or interface BaseClass // BaseClass obj = new BaseClass(); // These give compiler error // DerivedClass? is inaccessible due to its protection level // BaseClass.DerivedClass1 obj = new DerivedClass1(); // BaseClass.DerivedClass2 obj = new DerivedClass2(); // Output is // DerivedClass1 did something // DerivedClass2 did something // I don't know how to create 123 } } } </code> Charlie Poole [EMAIL PROTECTED] www.pooleconsulting.com www.charliepoole.org You can read messages from the Advanced DOTNET archive, unsubscribe from Advanced DOTNET, or subscribe to other DevelopMentor lists at http://discuss.develop.com.