Use template to simply codes and improve some codes