Head First Design Patterns

–选择自 calvinxiu 的 Blog 


    在更大的计划之前,先温习一下Design Pattern的功课。
    看了《Head First Design Patterns》里讲Decorator的样章,发现JOLT大奖不是白拿的,叙事能力之强,表达之清晰,不是那些满腹经伦的老先生可以比的。而且整个Pattern的讲述过程循序渐进,真的可以保证–小白都能学会设计模式。
    可惜就只有样章。Head First系列的电子书都不好找,只好还是翻出老先生们的书来看。
    这次温习很快做完,其实GOF80%的模式,都是基于一个原则:


    优先使用对象组合,而不是类继承.


    初学OO的人,都习惯用现实世界去映射程序世界,继承是最自然的思路。GOF其实就是在扭转这个思路,让大家习惯使用组合,委托和程序对象。

     组合机制只要根据两大原则,就可以变化出绝大部分的GOF模式.
     1.任何耦合都可以通过增加一个中间层来解耦
      代表模式有:   Facade , Mediator , Adapter  和 Factory/Abstract Factory , Proxy     
 
     2.通过组合来扩充对象特性,可以避免纯继承引起的类爆炸
      代表模式有:  Bridge , Decorator , Chain of Response , Strategy/Command


     3.另外还有些独立的常用模式如Singleton , Visitor , Observe


     写给自己看的重放慢镜:
    1.Facade : 为了减低一个系统和另一个系统的内部类之间的耦合性。建立对象A代理系统的主要功能


    2.Mediator:为了减低两个对象之间的耦合性。建立一个中间对象C,同时具有A和B的实例,并把C赋给A和B


    3.Adapter: 为了匹配不同的对象使用同一接口。建立对象B,代理A的方法并使其接口匹配。


    4.factory: 为了不依赖于具体对象而依赖于接口的创建对象。程序通过Factory获得对象。


    5.Proxy:   除了不依赖于具体对象,还能在过程中插入动作.程序通过Proxy调用对象的方法(AOP)


    6.Bridge:  如果对象特征向两个方向发展,Bridge能够避免两组对象特征的排列组合引起类爆炸。一组特征如大杯、中杯,一组特征如加奶、加糖。把其中一组特征抽象分离为接口2,把接口2的实例传入到主继承树中。


    7.Decorator: 通过包裹原对象,为原对象的动作添加新的动作。新类继承于原类,有原类同样的方法和原类的实体调用新类的方法时,会调用原类实体的原方法,再加上新类对其的扩展。


    8.COR:     通过安排职责链,让各对象根据情况添加自己的动作。每个对象都有下一个对象的指针,根据情况完成自己的操作后,把控制传给下一位。Apahce Jarkarta Commands有chains库。


    9.Strategy/Command: Template模式的对立物,把动作封装为对象进行组合。


    10.Observe: 通过一套机制,监控Observebal对象的状态变化。JDK实现了两套接口进行辅助。


    11.Visitor: 通过一套机制,让独立对象遍历组合里的所有对象,执行共同的动作。被访问对象有个accept(访问者)函数,在函数里面调用访问者.访问(this),不算很优雅的一个模式。



 


Leave a comment

长时间没有光顾,如今也应该写点东西了:)

可是,写点什么呢?

2 Comments

sybase 11.5 & 11.9.2 使用动态sql








sybase 11.5 & 11.9.2 使用动态sql
http://www.chinaunix.net 作者:azhe  发表于:2004-05-25 17:31:00





请教各位高手:  
“把一些sql语句片断(如表名,字段名,where条件等)作为字段放在数据表中,  
   在一个存储过程中,取出这些字段,并组成sql语句执行,  
   应如何实现?  
 “  
听说12.0以下11.5以上,用remote_sql这个系统过程模拟实现 ,能给我个例子吗?
 :!:


























 bluetune 回复于:2004-05-26 08:40:10
declare @table_name varchar(40)
declare @sql varchar(30)
declare @where_clause varchar(50)

select @table_name =  ’sysdatabases’
select @where_clause = ’where id = 1′

select @sql = ’select * from ’ + @table_name + @where_clause

exec(sql)




 azhe 回复于:2004-05-26 10:28:56
我的sybase版本11。5的,不能用exec这个命令啊。




 chenfeng825 回复于:2004-05-26 11:20:41
11.5和1192还没有支持动态sql,不过可以通过cis来模拟执行。具体做法如下:
执行CISXP_SETUP1.SQL并重启后执行CISXP_SETUP2.SQL,这两个脚本里面的server_name需要将自己的server_name替代既可以。
具体调用
参考附件




 chenfeng825 回复于:2004-05-26 11:30:21
附件没贴上去,具体看看下面的链接就好
http://www.sypron.nl/dynsqlcis.html




 azhe 回复于:2004-05-28 16:14:13
问题已经解决了!非常感谢!!




 zhangyh123 回复于:2004-05-29 00:42:48

:D  

不过 ,sp_remotesql的用法有 如下说法:
* Firstly define your local server to be a remote server using
    sp_addserver LOCALSRV,sql_server[,INTERFACENAME]
    go

  * Enable CIS
    sp_configure ”enable cis”,1
    go

  * Finally, use sp_remotesql, sending the sql to the server defined in point
    1.
    declare @sqlstring varchar(255)
    select @sqlstring = ”select count(*) from master..sysobjects”
    sp_remotesql LOCALSRV,@sqlstring
    go
—————————————————————————-
/*
 * CISXP_SETUP1.SQL
 *
 * Some server setups for CIS & XP. This will work only in ASE version 
 * 11.5 or later.
 * 
 * Note that you should first change this script: do a global change of 
 * the string ”YOUR_SERVER_NAME” to your actual SQL server name; ensure 
 * this is identical to the change in script CISXP_SETUP2.SQL.
 *
 * Note that there’s a server shutdown at the end.
 * After restarting the server, run script CISXP_SETUP2.SQL.
 * 
 *
 * Copyright note & Disclaimer :
 * =============================
 * This software is provided ”as is” – no warranty.
 * This software is for demonstration purposes only. It may not work correctly 
 * and/or reliably in a production environment.
 * You can use this software free of charge for your own professional, 
 * non-commercial purposes. 
 * You are not allowed to sell this software or use it for any commercial 
 * purpose. You may (re)distribute only unaltered copies of this software, which
 * must include this copyright note.
 *
 * Please send any comments, bugs, suggestions etc. to the below email address.
 *
 * (c) 1999 Copyright Rob Verschoor
 *                    Sypron B.V.
 *                    P.O.Box 10695
 *                    2501 HR Den Haag
 *                    The Netherlands
 *
 *                    Email: rob@sypron.nl
 *                    WWW  : http://www.euronet.nl/~syp_rob
 *—————————————————————————– 
 */

use master
go

/*
 * Check we’re on ASE 11.5 at least
 */
    if substring(@@version, 1, 26) != ”Adaptive Server Enterprise”
    begin
       print ”***” 
       print ”***” 
       print ”*** You can only use CIS and/or XP features on ASE version 11.5 or later.” 
       print ”*** These features do not exist in your current version of ASE, sorry…” 
       print ”***” 
       print ”***” 
    end
go

/*
 * Fix bug in definition of @@servername on ASE 11.5 
 * 
 * (If you created your server with the default Sybase 
 * ’srvbuild’ or ’srvbuildres’ tools, this will have 
 * been set up wrong. For an alternative, check out 
 * the free tool ”sybinit4ever” at
 * http://www.euronet.nl/~syp_rob/si4evr.html)
 */
if exists( select * from master..sysservers 
           where srvname=”local” )
  exec sp_dropserver local
go

if not exists( select * from master..sysservers 
               where srvid=0 )
  exec sp_addserver YOUR_SERVER_NAME, local
go

/*
 * add XP servername if not there yet
 * Note that the interfaces file should also contain an entry
 * for this XP server
 */
if not exists( select * from master..sysservers 
               where srvname=”YOUR_SERVER_NAME_XP” )
  exec sp_addserver YOUR_SERVER_NAME_XP, null, YOUR_SERVER_NAME_XP
go

/*
 * some config options to set up CIS & XP
 */
sp_configure ”enable cis”, 1 
go
sp_configure ”max cis remote connections”, 5
go

/*
 * now restart the server for these changes to take effect:
 */
shutdown
go

/* 
 * restart the server now, and run the script ”CISXP_SETUP2.SQL”
 */
===============================================================================

/*
 * CISXP_SETUP2.SQL
 *
 * Some server setups for CIS & XP. This will work only in ASE version 
 * 11.5 or later.
 *
 * First run script SETUP1.SQL and restart the server.
 * Then, run this script.
 *
 * Note that you should first change this script: do a global change of 
 * the string ”YOUR_SERVER_NAME” to your actual SQL server name; ensure 
 * this is identical to the change in script CISXP_SETUP1.SQL.
 * 
 *
 * Copyright note & Disclaimer :
 * =============================
 * This software is provided ”as is” – no warranty.
 * This software is for demonstration purposes only. It may not work correctly 
 * and/or reliably in a production environment.
 * You can use this software free of charge for your own professional, 
 * non-commercial purposes. 
 * You are not allowed to sell this software or use it for any commercial 
 * purpose. You may (re)distribute only unaltered copies of this software, which
 * must include this copyright note.
 *
 * Please send any comments, bugs, suggestions etc. to the below email address.
 *
 * (c) 1999 Copyright Rob Verschoor
 *                    Sypron B.V.
 *                    P.O.Box 10695
 *                    2501 HR Den Haag
 *                    The Netherlands
 *
 *                    Email: rob@sypron.nl
 *                    WWW  : http://www.euronet.nl/~syp_rob
 *—————————————————————————– 
 */
sp_configure ”xp_cmdshell context”, 0
go

/*
 * define a remote server which is actually pointing to yourself
 */
if not exists (select * from master.dbo.sysservers
               where srvname = ”YOUR_SERVER_NAME_MYSELF”)
   exec sp_addserver YOUR_SERVER_NAME_MYSELF, null, YOUR_SERVER_NAME
go

/*
 * set up remote access authorisation
 * There’s various ways of doing this. The proper one would be to
 * do ”sp_addexternlogin YOUR_SERVER_NAME_MYSELF, sa, sa, <sa-password>”.
 * Easier would be ”sp_addremotelogin YOUR_SERVER_NAME_MYSELF”, but there’s 
 * a built-in check that doesn’t allow this for local servers. So either
 * remove that check, or manually insert a row in master..sysremotelogins
 * as happens below. In the below case, this will allows all logins to 
 * do remote access. If you want only a specific login (say ’zzz’) to 
 * be enabled, insert the values (0,’zzz’,suser_id(‘zzz’),0).
 */
sp_configure ’allow updates’, 1
go

if not exists (select * from master.dbo.sysremotelogins
               where remoteserverid = 0
                 and remoteusername = NULL
                 and suid = -1
                 and status = 0)
    insert master.dbo.sysremotelogins values (0,null,-1,0) 
go

sp_configure ’allow updates’, 0
go

/* 
 * end
 */
============================================================================================
/* 
 * This script creates a procedure sp_exec_dynsql which will execute 
 * a string containg SQL statements.
 * This makes use of a CIS-related trick, to access the server as if it
 * were a remote server. This allows the use of dynamically 
 * generated SQL through sp_remotesql. 
 *
 * The purpose of this procedure is to demonstrate some of the 
 * CIS capabilities.
 *
 * Installation:
 * 1. First perform some server-level setups for CIS to work correctly. 
 *    These setups are in two scripts that can be downloaded from 
 *    http://www.euronet.nl/~syp_rob/cisxp_setup.html;
 *
 * 2. Next, run this script;
 *
 * 3. Finally, execute ”sp_exec_dynsql <string-with-SQL-cmds>”
 *
 *
 * Example:
 * ========
 * The below procedure ’myproc’ will select the specified column from
 * the specified table using ”sp_exec_dynsql” :
 *
 * create procedure myproc
 *  @col_name varchar(32),
 *  @tab_name varchar(70)
 * as
 * begin
 *   declare @cmd varchar(255)
 *   select @cmd = ”select ” + @col_name + ” from ” + @tab_name
 *   exec sp_exec_dynsql @cmd
 * end
 *
 * You can now do things like:
 *
 * 1> exec myproc ”pub_name”, ”pubs2..publishers”
 * 2> go
 *  pub_name
 *  —————————————-
 *  New Age Books
 *  Binnet & Hardley
 *  Algodata Infosystems
 * 
 *  (3 rows affected)
 *
 * 
 * Copyright note & Disclaimer :
 * =============================
 * This software is provided ”as is” – no warranty.
 * This software is for demonstration purposes only. It may not work correctly 
 * and/or reliably in a production environment. 
 * You can use this software free of charge for your own professional, 
 * non-commercial purposes. 
 * You are not allowed to sell this software or use it for any commercial 
 * purpose. You may (re)distribute only unaltered copies of this software, which
 * must include this copyright note.
 *
 * Please send any comments, bugs, suggestions etc. to the below email address.
 *
 * (c) 1999 Copyright Rob Verschoor / Sypron B.V.
 *                    P.O.Box 10695
 *                    2501 HR Den Haag
 *                    The Netherlands
 *
 *                    Email: rob@sypron.nl
 *                    WWW  : http://www.euronet.nl/~syp_rob
 *—————————————————————————– 
 */

use sybsystemprocs
go

/*
 * create sp_exec_dynsql
 */
if object_id(“sp_exec_dynsql”) <> NULL
begin
    drop procedure sp_exec_dynsql
end
go

create procedure sp_exec_dynsql
/* Copyright (c) 1999 Rob Verschoor/Sypron B.V. */
  @p_cmd varchar(255) = ”%”
as
begin
declare @remoteserver varchar(32)

   /* 
    * suppress rubbish 
    */
   set nocount on

   /* 
    * make sure this is 11.5 or later
    */
   if substring(@@version, 1, 26) != ”Adaptive Server Enterprise”
   begin
      print ”This procedure only works for ASE version 11.5 or later.”
      return (-1)
   end

   /* 
    * check server name is defined
    */
   if @@servername = NULL
   begin
      print ”The @@servername must be defined.”
      print ”Run ”"sp_addserver SERVERNAME, local”", and restart the server”
      return (-1)
   end

   /* 
    * Check a remote server is set up, pointing to the local server
    * (this is the basic trick that makes this whole procedure work)
    */
   select @remoteserver = srvname
   from master..sysservers
   where srvnetname = @@servername
     and srvname    != @@servername

   if (@@rowcount = 0) or (@remoteserver = ”")
   begin
      print ”A remote server must be set up in master..sysservers,”
      print ”pointing to this local server.”
      print ”First run the setup scripts CISXP_SETUP1.SQL & CISXP_SETUP2.SQL”
      print ”to fix this. These can be downloaded from”
      print ”http://www.euronet.nl/~syp_rob/cisxp_setup.html”

      return (-1)
   end

   /*
    * execute the specified command
*/
   exec sp_remotesql @remoteserver, @p_cmd

end
go
grant execute on sp_exec_dynsql to public
go

/*
 * end
 */


以上转自www.chinaunix.net


附件内容:














Simulating dynamic SQL through CIS
 
This is a demo of how you can use certain CIS (Component Integration Services) features in ASE 11.5 or 11.9 to simulate dynamic SQL.
ASE 12.0 contains a new feature called execute immediate which lets you execute a text string containing dynamically created SQL queries; however, this isn’t possible in ASE 11.5.x or 11.9.x. This demo shows how to achieve basically the same functionality in ASE 11.5.x / 11.9.x.

Below on this page, you can download SQL scripts which will create a stored procedure named sp_exec_dynsql. This procedure takes a text string as an argument and executes the SQL statements contained in the text string. Here’s an example: the below procedure myproc takes two arguments, being a column name and a table name. It will then select the specified column from the specified table using sp_exec_dynsql:
create procedure myproc
@col_name varchar(32),
@tab_name varchar(70)
as
begin
declare @cmd varchar(255)
select @cmd = “select ” + @col_name +
“from ” + @tab_name
exec sp_exec_dynsql @cmd
end
You can then do things like:
1> exec myproc “pub_name”, “pubs2..publishers”
2> go

pub_name
—————————————-
New Age Books
Binnet & Hardley
Algodata Infosystems

(3 rows affected)

Behind the scenes, this works as follows: using a CIS-related trick, you can access the local server as if it were a remote server. You can then use sp_remotesql to execute any command string in that not-so-remote server. Because sp_remotesql takes a text string as an argument, you can create any SQL statement dynamically and then execute it.
Note that you must be running ASE 11.5 or later (earlier versions do not have the CIS functionality included), and you must run set up the server for these tricks to work.

Note that there are also some other tricks to simulate dynamic SQL which will work in any ASE version, including versions 4.x, 10 and 11.0: go here to find out how to use it.


Installation instructions



  • Now you should run two setup scripts to prepare your server for using CIS: run CISXP_SETUP1.SQL, restart your server and then run CISXP_SETUP2.SQL. Note that you should ensure your @@servername matches your servername in the interfaces file.


  • Next, you can run the script SP_EXEC_DYNSQL.SQL, and then finally you’re ready to execute the procedure sp_exec_dynsql.

Posted in 文章:Sybase | Leave a comment

Sybase ASE12.5全局变量 by hobbylu

@@authmech
,@@monitors_active  
,@@version_number    
,@@msgschema
,@@msgreplytoinfo    
,@@msgstatusinfo
,@@msgstatus
,@@msgid
,@@msgtimestamp  
,@@msgproperties
,@@msgheader
,@@recovery_state    
,@@max_precision
,@@lock_timeout  
,@@datefirst
,@@tempdbid  
,@@bootcount
,@@boottime  
,@@bulkarraysize
,@@bulkbatchsize
,@@stringsize    
,@@invalidsuid  
,@@maxspid  
,@@minspid  
,@@version_as_integer    
,@@unicharsize  
,@@min_poolsize  
,@@heapmemsize  
,@@maxpagesize  
,@@invaliduserid
,@@guestuserid  
,@@probesuid
,@@maxgroupid    
,@@mingroupid    
,@@maxuserid
,@@minuserid
,@@maxsuid  
,@@minsuid  
,@@ha_local_nodeid  
,@@crthaproxy    
,@@errorlog  
,@@haconnection  
,@@failedoverconn    
,@@hacmpservername  
,@@cmpstate  
,@@remotestate  
,@@localstate    
,@@nodeid    
,@@curloid  
,@@textptr_parameters    
,@@transactional_rpc
,@@cis_rpc_handling  
,@@cis_version  
,@@scan_parallel_degree  
,@@parallel_degree  
,@@textcolid
,@@textdbid  
,@@textobjid
,@@textts    
,@@textptr  
,@@identity  
,@@mempool_addr  
,@@shmem_flags  
,@@kernel_size  
,@@kernel_addr  
,@@transtate
,@@char_convert  
,@@maxcharlen    
,@@client_csexpansion    
,@@client_csname
,@@client_csid  
,@@ncharsize
,@@thresh_hysteresis
,@@pagesize  
,@@langid    
,@@language  
,@@servername    
,@@isolation
,@@tranchained  
,@@textsize  
,@@spid  
,@@max_connections  
,@@dbts  
,@@timeticks
,@@options  
,@@total_errors  
,@@total_write  
,@@total_read    
,@@packet_errors
,@@connections  
,@@pack_sent
,@@pack_received
,@@idle  
,@@io_busy  
,@@cpu_busy  
,@@version  
,@@trancount
,@@nestlevel
,@@procid    
,@@rowcount  
,@@error
,@@sqlstatus

@@authmech
@@bootcount
@@boottime
@@bulkarraysize
@@bulkbatchsize
@@char_convert
@@cis_rpc_handling
@@cis_version
@@client_csexpansion
@@client_csid
@@client_csname
@@cmpstate
@@connections
@@cpu_busy
@@curloid
@@datefirst
@@dbts
@@error
@@errorlog
@@failedoverconn
@@guestuserid
@@hacmpservername
@@haconnection
@@heapmemsize
@@identity
@@idle
@@invaliduserid
@@io_busy
@@isolation
@@kernel_addr
@@kernel_size
@@langid
@@language
@@lock_timeout
@@maxcharlen
@@maxgroupid
@@maxpagesize
@@maxspid
@@maxsuid
@@maxuserid
@@max_connections
@@max_precision
@@mempool_addr
@@mingroupid
@@minspid
@@minsuid
@@minuserid
@@min_poolsize
@@monitors_active
@@ncharsize
@@nestlevel
@@nodeid
@@options
@@packet_errors
@@pack_received
@@pack_sent
@@pagesize
@@parallel_degree
@@probesuid
@@procid
@@recovery_state
@@rowcount
@@scan_parallel_degree
@@servername
@@shmem_flags
@@spid
@@sqlstatus
@@ssl_ciphersuite
@@stringsize
@@tempdbid
@@textcolid
@@textdbid
@@textobjid
@@textptr
@@textptr_parameters
@@textsize
@@textts
@@thresh_hysteresis
@@timeticks
@@total_errors
@@total_read
@@total_write
@@tranchained
@@trancount
@@transactional_rpc
@@transtate
@@unicharsize
@@version
@@version_as_integer

from http://bbs.chinaunix.net/forum/viewtopic.php?t=533042&show_type=new

Leave a comment

到现在为止,还不知道什么是RSS,惭愧:)

http://zh.wikipedia.org/wiki/RSS


另外的资料:


名词解释:什么是RSS?


  讨论与Blog相关的技术,不可不谈的就是RSS,这个缩写在英文中可以有几个源头,并被不同的技术团体做不同的解释。既可以是“Rich Site Summary”,或“RDF Site Summary”,也可以是“Really Simple Syndication”。为什么有这么多含义呢?这还要从RSS的一段今天也没有理清的关系说起。


  今天肯定有人还记得IE 4刚刚推出来的时候有一个有趣的功能,那就是新闻频道。这个新闻频道的功能与Netscape推出的新闻频道是很相似的(当时Netscape还是市场上领先的浏览器)。为此Netscape 定义了一套描述新闻频道的语言,这就是RSS,只不过Netscape自当时起每况愈下,所以最终也没有发布一个正式的RSS规范(只发布了一个0.9版本)。而微软也在当时推出了支持自己IE的CDF(Channel Definition Format)数据规格,与RSS非常接近。微软试图用新闻频道的功能把“推”(Push)技术变成一个应用主流,并与Netscape抗衡。不过出乎预测的是,“推”技术自始至终没有找到合适的商业模型,而且伴随着其他各类网络特性的出现,也日益无法显现自身的优势。新闻频道在浏览器中的地位最终日暮西山,最后也在IE的后续版本中消失了。


  新闻频道的确进入了低谷,但是RSS并没有被业界人士所抛弃。过去两年,Blog从一个专业群体开始,逐步成为了网络上最热门的新话题。而RSS成为了描述Blog主题和更新信息的最基本方法。于是RSS这项技术被著名Blogger/Geek戴夫·温那(Dave Winner)的公司UserLand所接手,继续开发新的版本,以适应新的网络应用需要。新的网络应用就是Blog,因为戴夫·温那的努力,RSS升级到了0.91版,然后达到了0.92版,随后在各种Blog工具中得到了应用,并被众多的专业新闻站点所支持。在广泛的应用过程中,众多的专业人士认识到需要组织起来,把RSS发展成为一个通用的规范,并进一步标准化。一个联合小组根据W3C新一代的语义网技术RDF对RSS进行了重新定义,发布了RSS 1.0,并把RSS定义为“RDF Site Summary”。这项工作并没有与戴夫·温那进行有效的沟通,而戴夫则坚持在自己设想的方向上进一步开发RSS的后续版本,也并不承认RSS 1.0的有效性。RSS由此开始分化形成了RSS 0.9x/2.0和RSS 1.0两个阵营,也由此引起了在专业人群中的广泛争论。


  因为争论的存在,一直到今天,RSS 1.0还没有成为标准化组织的真正标准。而戴夫·温那却在2002年9月独自把RSS升级到了2.0版本,其中的定义完全是全新的模式,并没有任何RSS 1.0的影子。这引发了网络上进一步争议,究竟让一个越来越普及的数据格式成为一个开放的标准,还是被一家公司所定义和控制,成为了争议的焦点。戴夫·温那并没有为自己辩解,他的观点是RSS还需要进一步发展,需要专业人士更明确的定义,不过恐怕这种轻描淡写不能消除人们对RSS“被一家商业公司独占”的担心。


  前面的铺垫对用户来说也许没有什么太大的意义,可能更多人关心如何在自己的Blog增加RSS输出,这样可以让很多新闻聚合工具(例如CNBlog刚刚推荐的NewzCrawler)很容易找到你并自动获得你在Blog中的更新内容。


  它是什么:站点用来和其他站点之间共享内容的简易方式(也叫聚合内容)。 RSS使肵ML作为彼此共享内容的标准方式。


  它代表什么:Really Simple Syndication (或RDF Site Summary,RDF站点摘要)


  例如:一些免费的软件能够让你阅读那些RSS使能的站点,比如 NewsIsFree 和 Amphetadesk。


  它有什么用处:让别人容易的发现你已经更新了你的站点,让人们很容易的追踪他们阅读的所有weblogs。

Leave a comment

[例程]Delegate声明的定义使用

[例程]Delegate声明的定义使用

作者: Builder.com
Thursday, August 12 2004 3:22 PM





本文译自Builder.com,未经许可请勿转载

如何定义一个delegate并且在何处使用?Tony Patton在本文中深入讨论了delegate











<A href="http://ad.cn.doubleclick.net/click%3Bh=v3|31cd|3|0|%2a|f%3B12037126%3B0-0%3B0%3B6694709%3B31-1|1%3B7654401|7672297|1%3B%3B%7Esscs%3D%3fhttp%3a%2f%2fhttp://www.net.cn/" target=_blank><IMG height=60 src="http://m2.cn.doubleclick.net/638159/MPU_revised1108.swf " width=468 border=0></A>

如何定义一个delegate并且在何处使用?Tony Patton在本文中深入讨论了delegate。


在最近有关.NET项目一次技术采访中,我被问到了关于定义术语的问题。由于项目是采用C#的.NET平台,所以问题就集中在C#上面。采访的过程非常有趣,但有一个特别的问题却是使我兴致大减,这一问题是:我是否必须定义delegate。虽然我已经广泛地使用它,但我还是很难从定义上回答。尽管我已经尽力回答,我还是感到事实尴尬。事实上,一个MCSD.NET应该能够毫无疑问地回答这样的问题。


delegate是什么?

根据微软的说法,一个delegate声明指定了一个相关的类型,你可以使用这一类型来封装一个含有特定标记的方法。一个delegate实例可以封装一个静态或一个实例方法。粗略的看来,Delegates就好象是C++中的函数指针;然而,delegates属于安全和保护类型。


我的采访是通过电话进行,所以我可以很容易和轻松地阐述这些定义。透明和详尽的解释是必须的。然而,作为贴切的delegates定义是,即使在没有对目标对象(target object)有任何了解的情况下,也可以随时使用某种方法,这样的方法即为delegates。很多开发人员通常将它们说成回调函数(callback functions)。现在让我们看一个范例,以更好理解它的应用。


应用中的Delegates

我们的范例程序开始于两个简单的C#类,这两个类包含一个方法以通过控制台来显示信息:


public class DelegateClass1 {


public void exampleMethod1(String passedString) {


Console.WriteLine(passedString); }


}


public class DelegateClass2 {


public void exampleMethod2(String passedString) {


Console.WriteLine(passedString); }


}


注意这两个类执行之间类似的方法。这些方法具有不同的名称,但它们的标记和实体都相同。你可以使用一个delegate来将这两个方法结合在一起,即通过定义一个从这两个方法的共同特性中抽象出新的数据类型。也就是它们都将一个简单的字符作为一个变量并返回void。C#中的delegate关键词使得一下语句成为可能:


public delegate void example(String passedString);


例如,使用这一新的数据类型声明,我们可以通过一个通用的抽象来调用这两个方法。下面的C#控制台程序利用了我们的delegate范例来调用这两个类的方法:


public class TestExampleDelegate {


public delegate void example(String passedString);


public static void Main(string[] args)  {


example[] items = new example[2];


items[0] = new example(new DelegateClass1().exampleMethod1);


items[1] = new example(new DelegateClass2().exampleMethod2);


for(int i = 0; i < items.Length; i++) {


items[i](“Builder.com Rules!”);


} } }


以上代码建立了一个数组的范例对象,并使用这些类中的方法实例化这些对象。由于忽略了括号,范例对象被一个调用方法处理。代码的执行结果显示了文本中(两次)。


(注意:Delegates不属于C#的细节;他们是.NET Framework的标准部分,所以也你可以使用其它的语言,比如VB.NET或者J#。)


Delegate无处不在











<A href="http://ad.cn.doubleclick.net/click%3Bh=v3|31cd|3|0|%2a|f%3B12037126%3B0-0%3B0%3B6694709%3B31-1|1%3B7654401|7672297|1%3B%3B%7Esscs%3D%3fhttp%3a%2f%2fhttp://www.net.cn/" target=_blank><IMG height=60 src="http://m2.cn.doubleclick.net/638159/MPU_revised1108.swf " width=468 border=0></A>


现在,也许你理解了它的原理,但却没有察觉它在你的程序代码中是如何应用的。尽管你没有建立自己的delegates,但如果你经常使用事件,你就一定会使用到他们。一个极好的例子就是ASP.NET中使用的事件。在后台使用的Delegates围绕着事件工作。事件使用一个一致标记,从而使delegate可用,你也可以在一个线程结构中找到delegates。


接口

你必须注意的另一个问题是一个delegate和一个接口之间的相似性,因为它们都将规范和执行分离开来。它们允许多个开发人员建立与规范相符合的执行。除此之外,方法标记必须被指定并且相互保持一致。


所以,在什么时候使用接口?以及什么时候使用delegates?微软提供了以下的指导思想。


在以下情况下使用Delegates很有用:


调用一个单一方法;


一个类要进行方法规范(method specification)的多种执行;


使用一个静态方法来执行规范;


想获得类似事件设计的模式;


调用者没有必要知道或获得方法定义的对象;


执行的提供者想将规范的执行“分发(hand out)”成一些可供选择的部分;


代码需要进行简单的组成部分。


接口在以下情况会很有用:


规范指定一套即将被调用的方法;


特别的,一个类只执行规范一次;


接口的调用者想通过接口类型以获得其它接口或类。


知识就是力量

这些关于开发的问题被谈论得如此严肃似乎有些可笑,但给出明确的定义或解释常常会比较困难。对于delegate的定义就是一个很好的例子。对于delegate特点的概述希望能够帮助你注意应当在何时何地使用它。同时,你也能够应付关于此类问题的采访。





本文作者:Tony Patton是作为一名应用程序开发人员开始其技术职业生涯的。他所通过的关于Java、VB、Lotus以及XML的认证大大的提高了他的技术水平。




[C#]
using System;
public class SamplesDelegate  {

   // Declares a delegate for a method that takes in an int and returns a String.
   public delegate String myMethodDelegate( int myInt );

   // Defines some methods to which the delegate can point.
   public class mySampleClass  {

      // Defines an instance method.
      public String myStringMethod ( int myInt )  {
         if ( myInt > 0 )
            return( “positive” );
         if ( myInt < 0 )
            return( “negative” );
         return ( “zero” );
      }

      // Defines a static method.
      public static String mySignMethod ( int myInt )  {
         if ( myInt > 0 )
            return( “+” );
         if ( myInt < 0 )
            return( “-” );
         return ( “” );
      }
   }

   public static void Main()  {

      // Creates one delegate for each method.
      mySampleClass mySC = new mySampleClass();
      myMethodDelegate myD1 = new myMethodDelegate( mySC.myStringMethod );
      myMethodDelegate myD2 = new myMethodDelegate( mySampleClass.mySignMethod );

      // Invokes the delegates.
      Console.WriteLine( “{0} is {1}; use the sign \”{2}\”.”, 5, myD1( 5 ), myD2( 5 ) );
      Console.WriteLine( “{0} is {1}; use the sign \”{2}\”.”, -3, myD1( -3 ), myD2( -3 ) );
      Console.WriteLine( “{0} is {1}; use the sign \”{2}\”.”, 0, myD1( 0 ), myD2( 0 ) );
   }

}

Posted in 文章:.NET | 1 Comment

Wikiup

黄夜青灯听夜雨,晨钟暮鼓诵经文。

Leave a comment

运动

在操场上慢跑了才不到三圈,就有点喘,唉,不服老不行啊;想当年,金戈铁马,气吞万里如虎。


该运动了,否则迟早会垮的。





1 Comment

自我原谅

好长时间没写东西了,时间总是在自我原谅中消逝……


真正理解了毛主席的一句名言:做一件好事并不难,难得是一辈子做好事。


风流总被雨打风吹去……

Leave a comment

驼铃 还是蒋大为的好听,李双江的简直没法比,差的不是一点半点。

          驼铃
送战友,踏征程。
默默无语两眼泪,
耳边响起驼铃声。
路漫漫,雾茫茫。
革命生涯常分手,
一样分别两样情。
战友啊战友,
亲爱的弟兄,
当心夜半北风寒,
一路多保重。
送战友,踏征程。
任重道远多艰辛,
洒下一路驼铃声。
山叠嶂,水纵横。
顶风逆水雄心在,
不负人民养育情。
战友啊战友,
亲爱的弟兄,
待到春风传佳讯,
我们再相逢。

1 Comment