1.新建一类库工程,命名为"vbnetdesignmode.vb" 2.将class1.vb删除 3.在此工程中添加类,命名为"factorymethod.vb" 4.在"factorymethod.vb"中添加产品类"product". (1)添加三个私有成员变量:mid,mname,mcreadate (2)添加三个公有属性:id,name,creadate *********************************************** factorymethod.vb代码如下: *********************************************** public class product '产品 '定义私有成员变量 private mid as integer private mname as string private mcreadate as datetime '定义属性 public property id() as integer get return mid end get set(byval value as integer) mid = value end set end property public property name() as string get return mname end get set(byval value as string) mname = value end set end property public property creadate() as datetime get return mcreadate end get set(byval value as datetime) mcreadate = value end set end property
********************************** factory.vb代码如下: ********************************** public class factory '工厂 '用overridable关键字定义createproduct方法,该方法返回一个product类的实例 '由于它有overridable关键字,其子类可用overrides关键字覆盖。 public overridable function createproduct() as product dim newproduct as new product() '进行产品类的初始化工作 newproduct.id = 99999 newproduct.name = "dreamfactoryno.1" newproduct.creadate = date.now return newproduct end function end class
9.将vs默认生成的form1.vb更名为"frmfactory.vb",最好也代码视图中的"public class form1()"改为"public class frmfactory()" 代码如下: public class frmfactory inherits system.windows.forms.form #region " windows 窗体设计器生成的代码 " 注:其中代码已省略 #end region end class
12.由于我们要对产品进行新的初始化操作,因此,我们将要覆盖createproduct方法. 前面我们说过,该方法之所以可以覆盖,是因为它是被overridable关键字来声明的. public class newfactory inherits vbnetdesignmode.factory public overrides function createproduct() as product dim newproduct as new product() '进行产品类的初始化工作 newproduct.id = 88888 newproduct.name = "dreamfactoryno.2" newproduct.creadate = date.now return newproduct end function end class
13.最后,我们在窗体的load中来分别测试:
private sub frmfactory_load(byval sender as system.object, byval e as system.eventargs) handles mybase.load dim oldpro as new product() dim oldfac as new factory() oldpro = oldfac.createproduct debug.writeline("********旧产品信息**********") debug.writeline(" id:" & oldpro.id) debug.writeline(" name:" & oldpro.name) debug.writeline(" creadate:" & oldpro.creadate)
dim newpro as new product() dim newfac as new newfactory() newpro = newfac.createproduct debug.writeline("********新产品信息**********") debug.writeline(" id:" & newpro.id) debug.writeline(" name:" & newpro.name) debug.writeline(" creadate:" & newpro.creadate) end sub